text:
Q: Query to find the missing dates of a month in Oracle Here are the dates available in my Record_Date (Date) column in  Attendance table in Oracle 10g.You can find the dates 04/06/2016 08/06/2016 16/06/2016 23/06/2016 29/06/2016 are missing in the sequence.
   **Record_Date**

    01/06/2016
    02/06/2016
    03/06/2016
    05/06/2016
    06/06/2016
    07/06/2016
    09/06/2016
    10/06/2016
    12/06/2016
    13/06/2016
    14/06/2016
    15/06/2016
    17/06/2016
    18/06/2016
    19/06/2016
    20/06/2016
    21/06/2016
    22/06/2016
    24/06/2016
    25/06/2016
    26/06/2016
    27/06/2016
    28/06/2016
    30/06/2016
    01/07/2016

I just need a query to find the missing dates in the specific month (and later also in the Year).
Kindly show me an approach

A: You can use this one:
WITH all_days AS
    (SELECT DATE '2016-06-01' + LEVEL-1 AS the_day
    FROM dual
    CONNECT BY DATE '2016-06-01' + LEVEL-1 <= DATE '2016-06-30')
SELECT the_day
FROM all_days
WHERE the_day <>ALL (SELECT Record_Date FROM Attendance);

Or, if you like to have it more dynamically:
WITH all_days AS
    (SELECT START_DATE + LEVEL AS the_day
    FROM dual
        CROSS JOIN
            (SELECT
                TRUNC(MIN(Record_Date), 'MM') -1 AS START_DATE,
                TRUNC(LAST_DAY(MAX(Record_Date))) AS END_DATE
            FROM Attendance)
    CONNECT BY START_DATE + LEVEL <= END_DATE)
SELECT the_day
FROM all_days
WHERE the_day <>ALL (SELECT Record_Date FROM Attendance);

Note, <>ALL is the same as NOT IN - it's just my personal preference.

A: with
nums(num )
as
(select 0 from dual
union all
select num + 1 from nums
  where num < (select max(col) from qtable)- (select min(col) from qtable)
),

date_btwn(dat)
as(select num + (select min(col) from qtable) from nums)

select  dat from date_btwn
minus
select col from qtable;

Inline views nums will generate all numbers to add from start date. date_btwn contains all dates between start date and end date in table. We are excluding the dates in our table using minus.

A: You need to generate all dates and you have to find missing ones. Below with  cte i have done it
Using CTE and not inQuery :
            with calendar as (
                    select rownum - 1 as daynum,
                    to_date('1-jun-2016') + (rownum - 1) as monthdate
                    from dual )
            select monthdate  as monthdate
            from calendar
            where monthdate  not in (
            SELECT
            Record_Date
            FROM Attendance      )
             and monthdate   >=  to_date('1-jun-2016')  /* CHANGE as per need */
             and monthdate   <  to_date('1-jul-2016')  /* CHANGE as per need */

Or Using CTE and left join Query :
            with calendar as (
                    select rownum - 1 as daynum,
                    to_date('1-jun-2016') + (rownum - 1) as monthdate
                    from dual )
            select monthdate  as monthdate
            from calendar C left join Attendance A on A.Record_Date=c.monthdate
            where A.Record_Date is  null
             and monthdate   >=  to_date('1-jun-2016')  /* CHANGE as per need */
             and monthdate   <  to_date('1-jul-2016')  /* CHANGE as per need */

as per datecolumn format change it to validformat into selection query first then use this query.


text:
Q: Knockout JS knockout validation plugin I have a viewModel with a property for a select. The property is placed inside a ko.validatedObservable({}). I am separating different Views with different ko.validatedObservable() sections. My inputs are validating fine except that the select is validating from page load even though in init() I have messagesOnModified: true (because I dont want to show error messages when first loading the page). The first option has value="". I checked the markup and the data-orig-title="REQUIRED" is set while the other input controls has this attribute set to "" as it should be
Could someone point out why the select behaves differently? I should also add that I am generating the Select with razor @Html.DropDownListFor(x=>x.dest_provincia, Model.Items, new { data_bind="dest_provincia"})
This is a sample of the validation
(on the viewModel)
self.dest_provincia = ko.observable().extend({ required: { message: "REQUIRED"} });

and this is placed inside:
self.userValidation = ko.validatedObservable({
        rem_provincia: this.rem_provincia
)};

I have noticed that the validation is happening on the select because a change event is being triggered, but I don't know what is making it..?
Update: I tried creating the select by razor, by looping on $.each in an ajax call and by filling an observableArray in knoackout. In any case the change event is trigger on page load...!?

A: I managed to solve this one today.
The problem exists between the razor engine templating the select options, and then later binding the value of the selected element to Knockout.
Despite the fact that there is no user-inputted value in the select box, the default value, the "--select--" actually contains a value. In my case it was an empty string. Therefore, when I applied the knockout bindings, my viewmodel property was "updated" with the empty string value, and therefore validation fired.
To get around this in my case I set the default value of my model to be an empty string. Therefore when the bindings are applied, there is no valueHasMutated event fired on the Knockout observable, and thus no validation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Play Game Service Mutli player Invitations not received I am currently working on a turn based multi player game and using Google Play Game Service for this. All set up has been made. Users can login properly and and select the players to compete with. After the selection when user presses Play button nothing special happens. onActivityResult shows that list of invitees has been prepared and match is created too on the defined criteria. I checked via logs. But on the invitee phone I never got any invitation. I checked on emulator (GenyMotion which serves Google Play Services compared to default emulator of Android SDk) and 2 different Android phones but unable to receive the invitation. I have setup as suggested here
https://developers.google.com/games/services/android/turnbasedMultiplayer
Below is my Code. Kindly anybody look into it and let me know where the problem is.
(P.S. I also came to know Invitations are sent via Google Cloud Messaging and I enabled this service for the game in Developer Console)
MultiPlayerInit.java
import java.util.ArrayList;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.google.example.games.basegameutils.BaseGameActivity;
import com.google.android.gms.common.api.*;
import com.google.android.gms.games.*;
import com.google.android.gms.games.Players.LoadPlayersResult;
import com.google.android.gms.games.multiplayer.Invitation;
import com.google.android.gms.games.multiplayer.Invitations;
import com.google.android.gms.games.multiplayer.Multiplayer;
import com.google.android.gms.games.multiplayer.OnInvitationReceivedListener;
import com.google.android.gms.games.multiplayer.Invitations.LoadInvitationsResult;
import com.google.android.gms.games.multiplayer.realtime.RoomConfig;
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatchConfig;
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMultiplayer.InitiateMatchResult;

public class MultiPlayerInit extends BaseGameActivity
implements OnClickListener {

    // For our intents
    final static int RC_SELECT_PLAYERS = 10000;
    final static int RC_LOOK_AT_MATCHES = 10001;
    final static int RC_INVITATION_INBOX = 10001;
    final static int REQUEST_ACHIEVEMENTS = 10002;
    String mIncomingInvitationId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.multiplayer_init);

        findViewById(R.id.sign_in_button).setOnClickListener(this);
        findViewById(R.id.sign_out_button).setOnClickListener(this);
        findViewById(R.id.btnInviteFriends).setOnClickListener(this);
        findViewById(R.id.btnGetInvitations).setOnClickListener(this);
    }

    @Override
    public void onSignInFailed() {
        // Sign in has failed. So show the user the sign-in button.
        findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
        findViewById(R.id.sign_out_button).setVisibility(View.GONE);
        findViewById(R.id.btnInviteFriends).setVisibility(View.GONE);
        findViewById(R.id.btnGetInvitations).setVisibility(View.GONE);

        Toast.makeText(getApplicationContext(), "Sorry! your sign-in attempt failed. Please check your credentials...", Toast.LENGTH_LONG).show();
        Log.v("Sign-in Failed","Sorry! your sign-in attempt failed. Please check your credentials...");
    }

    @Override
    public void onSignInSucceeded() {
        // show sign-out button, hide the sign-in button
        findViewById(R.id.sign_in_button).setVisibility(View.GONE);
        findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
        findViewById(R.id.btnInviteFriends).setVisibility(View.VISIBLE);
        findViewById(R.id.btnGetInvitations).setVisibility(View.VISIBLE);

        Games.Invitations.registerInvitationListener(getApiClient(), new OnInvitationReceivedListener() {

            @Override
            public void onInvitationRemoved(String arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onInvitationReceived(Invitation invitation) {
                // TODO Auto-generated method stub
                mIncomingInvitationId = invitation.getInvitationId();
                Toast.makeText(getApplicationContext(), "You have received an invitation from: "+invitation.getInviter().getDisplayName()+" with ID: " +mIncomingInvitationId, Toast.LENGTH_LONG).show();
            }
        });

        Toast.makeText(getApplicationContext(), "You are now logged in successfully...", Toast.LENGTH_LONG).show();
        Log.v("Sign-in Succeeded","You are now logged in successfully...");
        // (your code here: update UI, enable functionality that depends on sign in, etc)
    }

    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.sign_in_button) {
            // start the asynchronous sign in flow
            beginUserInitiatedSignIn();
        }
        else if (view.getId() == R.id.sign_out_button) {
            // sign out.
            signOut();

            // show sign-in button, hide the sign-out button
            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_button).setVisibility(View.GONE);
            findViewById(R.id.btnInviteFriends).setVisibility(View.GONE);
            findViewById(R.id.btnGetInvitations).setVisibility(View.GONE);
        }
        else if (view.getId() == R.id.btnInviteFriends) {

            Intent intent = Games.TurnBasedMultiplayer.getSelectOpponentsIntent(getApiClient(), 1, 3);
            startActivityForResult(intent, RC_SELECT_PLAYERS);
        }

        else if (view.getId() == R.id.btnGetInvitations) {

            Intent intent =
                    Games.TurnBasedMultiplayer.getInboxIntent(getApiClient());
                startActivityForResult(intent, RC_INVITATION_INBOX);

        }
    }

    @Override
    protected void onActivityResult(int request, int response, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(request, response, data);

        if (request == RC_SELECT_PLAYERS) {
            if (response != Activity.RESULT_OK) {
                // user canceled
                return;
            }

            // get the invitee list
            final ArrayList<String> invitees =
                    data.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);

            // get auto-match criteria
            Bundle autoMatchCriteria = null;
            int minAutoMatchPlayers = data.getIntExtra(
                    Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
            int maxAutoMatchPlayers
                    = data.getIntExtra(
                    Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);
            if (minAutoMatchPlayers > 0) {
                autoMatchCriteria
                        = RoomConfig.createAutoMatchCriteria(
                        minAutoMatchPlayers, maxAutoMatchPlayers, 0);
            } else {
                autoMatchCriteria = null;
            }

            TurnBasedMatchConfig tbmc = TurnBasedMatchConfig.builder()
                    .addInvitedPlayers(invitees)
                    .setAutoMatchCriteria(autoMatchCriteria).build();

            Games.TurnBasedMultiplayer
                .createMatch(getApiClient(), tbmc)
                .setResultCallback(new MatchInitiatedCallback());

        }
    }
}

AndroidManifest.xml
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xetree.guesspicwithfriends"
    android:versionCode="3"
    android:versionName="2.0" >

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="18" />
    <uses-permission android:name="com.android.vending.BILLING" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.GET_TASKS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <meta-data android:name="com.google.android.gms.version"
                    android:value="@integer/google_play_services_version" />

        <meta-data android:name="com.google.android.gms.games.APP_ID"
                    android:value="@string/app_id" />

        <activity android:name="com.xetree.guesspicwithfriends.HomeActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/app_name"
            android:theme="@style/AppBaseTheme"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.xetree.guesspicwithfriends.MultiPlayerInit"
                    android:screenOrientation="portrait" />
        </application>

</manifest>

A: The request does not go out until you call takeTurn().
TurnBasedTurnBasedMultiplayer


text:
Q: Configure htaccess to symfony project I have a hosting with my personal project in Symfony2 installed it inside a folder "public_html", then when I want to access to my project I have to write the next
url: "mydomian.net/myprojectSymfony/web/", instead of "mydomain.net".
If I just write mydomain.net the server shows me the directory "public_html" with all folders inside him. How can I write my .htaccess file to solve this problem?
I tried with Redirect 301 but I don't know if the right way.

A: In my opinion the best approach is to configure your apache vhost as explained there:
http://symfony.com/doc/current/cookbook/configuration/web_server_configuration.html
<VirtualHost *:80>
    ServerName mydomain.net
    ServerAlias www.mydomain.net

    DocumentRoot /var/www/myprojectSymfony/web
    <Directory /var/www/myprojectSymfony/web>
        AllowOverride All
        Order Allow,Deny
        Allow from All
    </Directory>

    ErrorLog /var/log/apache2/project_error.log
    CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>


text:
Q: Some of fn keys not recognized after upgrade After upgrading my system (including kernel) I discovered that some of fn keys (XF86MonBrightnessUp and XF86MonBrightnessDown) are not recognized by xev and even showkey. Each time one of these keys is pressed the next message appears in dmesg output:
[ 429.202833] atkbd serio0: Unknown key pressed (translated set 2, code 0x88 on isa0060/serio0).
[ 429.202847] atkbd serio0: Use 'setkeycodes e008 <keycode>' to make it known.

I executed setkeycodes e008 <keycode> after that showkey started to show key code, however xev still cannot recognize that key was pressed.
One more detail which was discovered using evtest tool is that problematic keys generate only events with value 2:
Event: time 1430520388.854296, type 4 (EV_MSC), code 4 (MSC_SCAN), value 89
Event: time 1430520388.854296, type 1 (EV_KEY), code 224 (KEY_BRIGHTNESSDOWN), value 2

At the same time all other keys generate events with value 0, value 1 and value 2:
Event: time 1430520477.865671, type 4 (EV_MSC), code 4 (MSC_SCAN), value b0
Event: time 1430520477.865671, type 1 (EV_KEY), code 115 (KEY_VOLUMEUP), value 1
Event: time 1430520477.865671, -------------- SYN_REPORT ------------
Event: time 1430520478.115796, type 4 (EV_MSC), code 4 (MSC_SCAN), value b0
Event: time 1430520478.115796, type 1 (EV_KEY), code 115 (KEY_VOLUMEUP), value 2
Event: time 1430520478.115796, -------------- SYN_REPORT ------------
Event: time 1430520478.148696, type 4 (EV_MSC), code 4 (MSC_SCAN), value b0
Event: time 1430520478.148696, type 1 (EV_KEY), code 115 (KEY_VOLUMEUP), value 2
Event: time 1430520478.148696, -------------- SYN_REPORT ------------
Event: time 1430520478.377785, type 4 (EV_MSC), code 4 (MSC_SCAN), value  b0
Event: time 1430520478.377785, type 1 (EV_KEY), code 115 (KEY_VOLUMEUP), value 2
Event: time 1430520478.377785, -------------- SYN_REPORT ------------
Event: time 1430520478.387684, type 4 (EV_MSC), code 4 (MSC_SCAN), value b0
Event: time 1430520478.387684, type 1 (EV_KEY), code 115 (KEY_VOLUMEUP), value 0
Event: time 1430520478.387684, -------------- SYN_REPORT ------------

As I wrote above, a kernel upgrade also took place (3.19.3 -> 4.0.1). However now I encounter the same issue even on the old kernel.
I guess the list of changes during update is necessary, so here I provide it: http://fixee.org/paste/zrm8kl2/
TIA


text:
Q: Regex to strip all directorynames from Path (leave filename) I want to remove all directorynames from a path:
Payload/brownie.app/Info.plist

should become
Info.plist

What regex should I use or can I use replace() from String in java?
thanks!

A: This covers all spectrums directories, trailing or starting slashes.
All others here so far does not...
public static String extractFilename(String path)  {
    java.util.regex.Pattern p       = java.util.regex.Pattern.compile('^[/\\\\]?(?:.+[/\\\\]+?)?(.+?)[/\\\\]?$');
    java.util.regex.Matcher matcher = p.matcher(path);

    if ( matcher.find() ) {
        return matcher.group(1);
    }
    return null;
}

Used:
println extractFilename("data\\\\path/to/file/RandomFile.pdf")
println extractFilename("RandomFile.pdf")
println extractFilename("RandomFile.pdf/")
println extractFilename("data\\\\path/to/file/RandomFile.pdf/")
println extractFilename("/data\\\\path/to/file/RandomFile.pdf/")
println extractFilename("/data\\\\path/to/file/RandomFile.pdf")
println extractFilename("/RandomFile.pdf")
println extractFilename("/RandomFile.pdf/")
println extractFilename("/")

Prints
RandomFile.pdf
RandomFile.pdf
RandomFile.pdf
RandomFile.pdf
RandomFile.pdf
RandomFile.pdf
RandomFile.pdf
RandomFile.pdf
/

.......................................................................EDIT............................................................................
Explanation for Uday. It was actually pretty complicated one, and I am not sure I can argue for all of it today, but I will give it a try :)
^[/\\\\]?(?:.+[/\\\\]+?)?(.+?)[/\\\\]?$

0: Entire regex
^

1: Starts with
[/\\\\]?

2: A forward slash or backward slash ( yes, four slashes for one, crazy! ). Once or not at all, so not required.
(?:.+[/\\\\]+?)?

3: This step is the complicated one. It is intended to skip everything but the last one that matches this exact pattern, a non capturing group (?:... were we are looking for any character several times, followed by one slash.
The group can be repeated many times, but it is non greedy. So it is saying do this, except until you match the following regex explained in 4.
This entire piece though, is not required, because of the ? outside the parentheses. For instance, "/RandomFile.pdf/" will not generate a match here, and continue with 4.
However, now I do find this a bit weird, since .+ is greedy, still it is looking forward to the slash for the match. It might be the nature of groups, that they are non-greedy or a bug in Java pattern syntax.
(.+?)[/\\\\]?$

4: Since the regex applies for all of the string, it also has to match up to the end. The previous match at 3 was non greedy, reluctant using +?, meaning it will only match as long as the regex after it doesn't also match. Our word is at the end $ is within the parentheses which may or may not end with a slash. I have chosen to return the root path as the file name if there is no filename, but just a slash, since it is also a filename ( directory name )
5: The parentheses is a capturing group, which is what we return at the end.
I hope this clarifies a bit.

A: Use replace with regex,  String name = directory.replaceAll(".*/",""), simple as that.

A: Try with this:
new File("Payload/brownie.app/Info.plist").getName()

This returns the filename without directories.
Example:
String filename = new File("Payload/brownie.app/Info.plist").getName();
System.out.println(filename);

Outupt:
Info.plist

A: You don't need a regex. Just find the last slash and use substring:
int index = path.lastIndexOf(File.separatorChar);
String name = path.substring(index+1);

or use:
new File(path).getName();

A: The previous answers are all simpler than using a full-blown regular expression. If you really want to use one, though, here's a regex pattern you could use: ".*/(.+)"
    Pattern p = Pattern.compile(".*/(.+)");
    Matcher matcher = p.matcher("Payload/brownie.app/Info.plist");

    if ( matcher.find() ) {
        System.out.println("result: "+matcher.group(1));
    }

As you can see from the other answers, this is more code than is strictly needed, but if you are doing more sophisticated pattern matching and string extraction then regular expressions are a good way to go.

A: If you're dealing with a file path that's been passed by a browser to a web server, you can't be sure if it'll be a DOS style path, Unix style, or just a filename without path. If you really want a RegEx, this should do it:
String path = "Payload/brownie.app/Info.plist";
String filename = path.replaceFirst("(^.*[/\\\\])?([^/\\\\]*)$","$2");

This will work whether there's a DOS, Unix, or absent path.
It'd be more legible, though, to use substrings as dogbane suggests, but adding logic to check for both types of file separator (again, only if you're dealing with multi-platform input).


text:
Q: What is the most computationally efficient method to recursively calculate the Fibonacci sequence? Here is the code I currently have.
def fibonacci(n):

    if n == 1:
        return 1
    elif n == 2:
        return 1
    else:
        value = fibonacci(n - 1) + fibonacci(n - 2)
        return value

This currently takes quite some time to calculate values greater than n = 30. Is there a more computationally efficient method to accomplish this?

A: Adding a value cache to trade some memory for a reduced processing time can be a useful method. A purely recursive program will attempt to calculate values over and over again, however this takes time for larger values. If the values do not change, then storing them can be helpful. It is important to note, however, that should values be volatile you might need a different approach.
fibonacci_value_cache = {}

def fibonacci(n):

    if n == 1:
        return 1
    elif n == 2:
        return 1
    elif n in fibonacci_value_cache:
        return fibonacci_value_cache[n]
    else:
        fibonacci_value_cache[n] = fibonacci(n - 1) + fibonacci(n - 2)
        return fibonacci_value_cache[n]

n = 100

print("Fib " + str(n) + ": " + str(fibonacci(n)))

Here, we check if the value is in the dictionary and return it if it is, otherwise we calculate it and add it to the dictionary. This means that we are make better use of the processor by not calculating the same value multiple times.

A: Using idea of Dynamic Programming, and store the intermediate results to save computational cost, it could be very efficient. The code below cost less than 0.02s for n=10000 on my laptop.
def fib(n):  # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    for i in range(n):
        result.append(b)
        a, b = b, a + b
    return result

A: There's a recipe for  a decorator that uses as an example exactly what you want. It's named Memoize in the PythonDecoratorLibrary.
It may seem like overkill, but having the memoized decorator around could be useful for other future tasks. That said, here it is in its entirety (although I changed the print at the end):
import collections
import functools

class memoized(object):
   '''Decorator. Caches a function's return value each time it is called.
   If called later with the same arguments, the cached value is returned
   (not reevaluated).
   '''
   def __init__(self, func):
      self.func = func
      self.cache = {}
   def __call__(self, *args):
      if not isinstance(args, collections.Hashable):
         # uncacheable. a list, for instance.
         # better to not cache than blow up.
         return self.func(*args)
      if args in self.cache:
         return self.cache[args]
      else:
         value = self.func(*args)
         self.cache[args] = value
         return value
   def __repr__(self):
      '''Return the function's docstring.'''
      return self.func.__doc__
   def __get__(self, obj, objtype):
      '''Support instance methods.'''
      return functools.partial(self.__call__, obj)

@memoized
def fibonacci(n):
   "Return the nth fibonacci number."
   if n in (0, 1):
      return n
   return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(12))

A: No need for caching/memoization.  Here's a Python 3 implementation that expresses the Fibonacci sequence as powers of a matrix, then does efficient exponentiation via halving and squaring.  The result is O(log n) in both time and storage.
def matrix_fib(n):
    if n == 1:
        return [0,1]
    else:
        f = matrix_fib(n // 2)
        c = f[0] * f[0] + f[1] * f[1]
        d = f[1] * (f[1] + 2 * f[0])
        return [c,d] if (n & 1) == 0 else [d,c+d]

def fib(n):
  return n if n == 0 else matrix_fib(n)[1]

print(fib(1000000))

On my laptop this coughs up the value of the millionth Fibonacci number in a little over half a second, and the bulk of that is probably in the big integer arithmetic and formatting of the output—the result is ridiculously large. You don't need to worry about stack overflow, though.  The call stack depth for this is only log2(1000000) = 20.


text:
Q: FlatList does not pass through 0 or null into renderItem prop If I try to render a FlatList like so:
<View>
   <FlatList
     numColumns={2}
     data={[1, 0, 3, null]}
     renderItem={(itemData, idx) => <Text key={idx}>{itemData.item}</Text>}
     horizontal={false}
   />
</View>

The only thing returned would be 1 and 2 (except they take up space in the row/column as if the other values had rendered as well–they stack up in a column). I have no access to the 0 value or the null value (so I can't conditionally render something else, i.e. return itemData.item || 'No Data'.
If I try this (with slightly less props):
<View>
    <FlatList
      data={[1, 0, 3, null]}
      renderItem={(itemData, idx) => <Text key={idx}>{itemData.item}</Text>}
    />
</View>

I get an error Invariant Violation: No item for index 2.
Is there a solution besides looping through the data beforehand and replacing all 0's with a string "0" and all nulls, undefined, empty strings etc. with a string "null" and conditionally rendering with that: return itemData.item !== 'null' ? itemData.item || 'No Data'

A: It looks like when you try to access itemData.0 it understands as false instead of number 0, the same logic looks to be applied when trying to access itemData.null value.
If you add a console.log to your renderItem, you can confirm if what I said is correct
renderItem={(itemData, idx) => {
  console.log('Trying to render item: ', idx);
  return <Text key={idx}>{itemData.item}</Text>;
}}

Supposing this is the case, then you can achieve what you want by something like this:
renderItem={(itemData, idx) => itemData.item && <Text key={idx}>{itemData.item}</Text>}
Hope it helps


text:
Q: Trouble adding JavaScript in visual editor (Sharpspring embed code) I am trying to add the embed code for a sharpspring form signup to my site. It says that it works with WordPress but when I add the code to the text section of the page and save the script tags are removed and the code is posted as plain text.
 <script type="text/javascript">
    var ss_form = {'account': '**********', 'formID':'****************'};
    ss_form.width = '100%';
    ss_form.height = '1000';
    ss_form.domain = 'app-3QMYP5URE0.marketingautomation.services';
    // ss_form.hidden = {'Company': 'Anon'}; // Modify this for sending hidden variables, or overriding values
</script>
<script type="text/javascript" src="https://koi-3QMYP5URE0.marketingautomation.services/client/form.js?ver=1.1.1"></script>

How would I add this form to the page so that the form shows?

A: You need the unfiltered_html capability to write JavaScript in post content. This is granted by default to administrators and editors.
The better way would be to write a small plugin that provides you a shortcode:
<?php

/**
 * Plugin Name: WPSE 234978 – Provide shortcode for Sharpspring embed
 * Plugin URL:  http://wordpress.stackexchange.com/q/234978/31323
 * License:     MIT
 * Version:     1.0.0
 * Author:      David Naber
 */

namespace WPSE234978;

add_action(
    'wp_loaded',
    function () {
        /**
         * Register the shortcode '[sharpspring_embed]'
         */
        add_shortcode( 'sharpsrpring_embed', __NAMESPACE__ . '\sharpspring_embed_shortcode' );
    }
);

/**
 * Translates the shortcode to the sharpspring embed code
 *
 * @return string
 */
function sharpspring_embed_shortcode() {

    $embed = <<<HTML
<script type="text/javascript">
    var ss_form = {'account': '**********', 'formID':'****************'};
    ss_form.width = '100%';
    ss_form.height = '1000';
    ss_form.domain = '***********';
    // ss_form.hidden = {'Company': 'Anon'}; // Modify this for sending hidden variables, or overriding values
</script>
<script type="text/javascript" src="https://********.marketingautomation.services/client/form.js?ver=1.1.1"></script>
HTML;

    return $embed;
}

Create a new directory inside wp-content/plugins and name it to something like $YOURSITE-sharpspring-embed. Create a PHP file inside (name it like $YOURSITE-sharpspring-embed) that directory and paste the code above into that file. Remember to replace your credentials and app IDs.
Then activate the plugin and use the shortcode [sharpspring_embed] in your post content.
Note: that plugin requires at least PHP version 5.3 (today 5.6 is the current stable version).


text:
Q: Creating a subset from a dataframe based on a condition from another array I have a numeric np array which I want to use that as a condition/filter over a column number 4 of a dataframe (df) to extract a subset of dataframe (sale_data_sub). However, I am getting an empty sale_data_sub (with just the name of all the columns and no rows) as a result of the code
     sale_data_sub = df.loc[df[4].isin(sale_condition_arr)].values

sale_condition_arr is a numpy array
df is the original dataframe with 100 columns
sale_data_subset is the desired sub_dataframe
Sorry that I didn't include a working sample.

A: the issue is that your df dataframe don't have headers assigned.
try:
#give your dataframe a header:
df = df.set_axis([str(i) for i in list(range(len(df.columns)))], axis='columns')

#then proceed to your usual work with df:
sale_data_sub = df.loc[df["4"].isin(sale_condition_arr)].values #be careful, it's df["4"] not df[4]


text:
Q: How would you get the Sql Command objects for a Given TableAdaptor and SqlDataAdaptor in C# (.NET 2.0) I am creating a generic error handling / logging class for our applications. The goal is to log the exception info, info about the class and function (as well as parameters) and if relevant, the information about the System.Data.SqlClient.SqlCommand object.
I would like to be able to handle passing in SqlCommands, TableAdaptors, and SqlDataAdaptors.
I am new to using reflection and I know that it is possible to do this, I am just not sure how to go about it. Please advise.

A: Is this what you're talking about?
SqlDataAdapter da = new SqlDataAdapter();
var cmd1 = ((IDbDataAdapter)da).DeleteCommand;
var cmd2 = ((IDbDataAdapter)da).UpdateCommand;
var cmd3 = ((IDbDataAdapter)da).SelectCommand;
var cmd4 = ((IDbDataAdapter)da).InsertCommand;

The SqlDataAdapter implements IDbDataAdapter, which has getters/setters for all the CRUD commands.  The SqlDataAdapter implements these explicitly, so they don't show up in the signature of the class unless you first cast it to the interface.  No reflection necessary.


text:
Q: c# how to get tables in the footer of a word document I got some problems with the Microsoft office library in C#. When I try to get the table present in my first page's footer, the programme cannot find it, I can only get the table in text format :
object nom_fi = (object)chemin;
object readOnly = false;
object isVisible = false;
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref nom_fi, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
doc.Activate();

foreach (Microsoft.Office.Interop.Word.Section sec in doc.Sections)
{
    Microsoft.Office.Interop.Word.Range range = sec.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
    Microsoft.Office.Interop.Word.Table t = range.Tables[0];
}
doc.Close();

Thanks for your attention
EDIT : exception :

It says : "Member of required collection does not exists"

A: If your section is setup to feature a different first page header/footer, you would need to get that particular first page footer using wdHeaderFooterFirstPage:
Range range = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range;

If you don't know the section/page setup of your document, you can get the range of the footer that appears on the first page as follows:
Range range;
if (sec.Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Exists)
{
    range = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range;
}
else
{
    range = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
}

Note that the table index starts at 1 (something already mentioned in the comments), so that you will need to adjust your code to Table t = range.Tables[1];

Note that you can make your code a lot more readable by importing namespaces with using directives at the top of your file, by omitting optional parameters, and by removing the explicit object declarations (the latter things were required only in early versions of .NET):
using Microsoft.Office.Interop.Word;

var wordApp = new Application();
var doc = wordApp.Documents.Open(chemin, ReadOnly: false, Visible: false);
doc.Activate();

foreach (Section sec in doc.Sections)
{
    var range = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range;
    var table = range.Tables[1];
}

doc.Close();


text:
Q: EXCEL: Generate a row with unique data from multiple columns I have a matrix of data in Excel and I want to write in a row the unique values in that data using only formulas.  Most of the formulas I have found so far write the unique values into a column and takes the data from a single column. I attach an image of an example of what I need.
In the example the data is in B2:D4 and the unique results will be printed in F2:I2, thank you in advance for the help

A: The closest I can get is to give you a unique list in order of largest to smallest:
=AGGREGATE(14,6,$B$2:$D$4/(COUNTIF($E$2:E2,$B$2:$D$4)=0),1)

A: Apply this array formula in F2 with CSE,
=IFERROR(INDEX($B$2:INDEX($B:$B, MATCH(1E+99, $B:$B)), MATCH(0, COUNTIF($E2:E2, $B$2:INDEX($B:$B, MATCH(1E+99, $B:$B))), 0)),
 IFERROR(INDEX($C$2:INDEX($C:$C, MATCH(1E+99, $C:$C)), MATCH(0, COUNTIF($E2:E2, $C$2:INDEX($C:$C, MATCH(1E+99, $C:$C))), 0)),
 IFERROR(INDEX($D$2:INDEX($D:$D, MATCH(1E+99, $D:$D)), MATCH(0, COUNTIF($E2:E2, $D$2:INDEX($D:$D, MATCH(1E+99, $D:$D))), 0)), TEXT(,))))

... and fill right.

A: With data in B2 through D4, in F2 enter:
=MIN($B$2:$D$4)

and in G2 enter the Array Formula:
=MIN(IF($B$2:$D$4>F2,$B$2:$D$4))

and copy across:

Array formulas must be entered with Ctrl + Shift + Enter rather than just the Enter key.

A: Do you have to do it using only formulas?  The Remove Duplicates function under the Data tab sounds perfect for this sort of problem.  I am not sure if Remove Duplicates can produce horizontal data, but the transpose function can easily solve that.


text:
Q: How to initialize an Array in Pascal? In Java we can initialize an array by following code:
data[10] = {10,20,30,40,50,60,71,80,90,91};

But in Pascal how can we do this?

A: Here's a full example program that compiles at http://www.onlinecompiler.net/pascal for both Windows and Linux.
program test;
var
    data: array[0..9] of integer = (10,20,30,40,50,60,71,80,90,91);
begin
    writeln('Hello World');
    writeln(data[0]);
end.


text:
Q: Capture live video from a DSLR in C++/OpenCV My C++/OpenCV app runs well when I use a USB webcam to capture live video stream.
However, when I connect a Canon 5Dii with live video it doesn't find the camera.
The Canon utility captures the video well.
Should I use the VideoCapture cap(1)?

A: You should use the official Canon Digital Camera SDK to grab frames from 5D II. There are some sample apps for connecting to the camera (as a source device) from your PC and then receiving camera events/images. Keep in mind that you need to sign up and be approved by Canon to use the SDK.


text:
Q: How to handle the message-only window to get the messages from the console window? I'm trying to know when a console window has moved so I created a new message-only window to get the messages of the console but I don't know if it is working because the message is apparently never being received.
#define WINVER 0x0501
#include <windows.h>
#include <iostream>

WNDPROC glpfnConsoleWindow; // NEW
using namespace std;

LRESULT APIENTRY MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_SIZE:
        cout<<"Window moved"<<endl;
        break;
        case WM_DESTROY:
        PostQuitMessage(0);
        break;
        default:
        // NEW
        return CallWindowProc(glpfnConsoleWindow, hwnd, uMsg, wParam, lParam);
        //return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    HWND hwnd;
    MSG Msg;
    const char lpcszClassName[] = "messageClass";
    WNDCLASSEX  WindowClassEx;

    // == NEW
    HWND consHwnd;
    consHwnd = GetConsoleWindow();
    glpfnConsoleWindow = (WNDPROC)SetWindowLong(consHwnd, GWL_WNDPROC, (LONG)MainWndProc);
    // ==

    ZeroMemory(&WindowClassEx, sizeof(WNDCLASSEX));
    WindowClassEx.cbSize        = sizeof(WNDCLASSEX);
    WindowClassEx.lpfnWndProc   = MainWndProc;
    WindowClassEx.hInstance     = hInstance;
    WindowClassEx.lpszClassName = lpcszClassName;

    if (RegisterClassEx(&WindowClassEx) != 0)
    {
        // Create a message-only window
    hwnd = CreateWindowEx(0, lpcszClassName, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL);
        if (hwnd != NULL)
        cout<<"Window created"<<endl;
        else
        UnregisterClass(lpcszClassName, hInstance);
    }
    ShowWindow(hwnd,nCmdShow);
    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
     return (int)Msg.wParam;
}

A: Perhaps you should process WM_MOVE, which, according to the documentation, is sent after the window has been moved. WM_SIZE is sent when the size changes.
I think your problem is that the WM_MOVE and WM_SIZE messages are going to the console window rather than to your hidden window.
I suspect you'll have to call GetConsoleWindow to get the console window handle, and then call SetWindowLong to attach your window proc to the console window. Be sure to pass messages on to the original window proc.


text:
Q: AWS PHP SDK V2 dynamodb - how to disable/enable ssl How do I disable/enable SSL when working with dynamodb with the new PHP SDK (V2).
In V1 there was $DDB->disable_ssl();  Whats the equivalent on V2 ?
Couldn't find anything on this in the documentation.

A: While it is not recommended, you can disable SSL by passing a scheme option to a client's factory method or as a configuration setting in a service builder.
<?php

$client = Aws\DynamoDb\DynamoDbClient::factory(array(
  'key'    => '***',
  'secret' => '***',
  'region' => 'us-east-1',
  'scheme' => 'http'
));

The scheme option determines the URL scheme used when creating the base URL used to contact a service.


text:
Q: Procesar eventos con un sólo toString();
Buenas. Estoy haciendo un ejercicio que consiste en generar diversos tipos de eventos y generar un toString() que indique una descripción de lo que generó el evento. Supuse que al implementar las diversas interfaces podría crear una variable de mi clase para alojar los diferentes eventos y llamar al toString() de mi clase pero he advertido que el tipo de la interfaz y el del evento que se maneja no es el mismo con lo que mi variable no funciona. Pregunta: hay alguna forma de procesar diferentes eventos con un sólo String?
  Ahí está la pequeña chapucilla que intentaba...(Generador es mi clase y gen la variable de ella)

 public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

    gen=(Generador)e.getSource();
    System.out.println(e.getActionCommand()+""+gen.toString());
}

A: El método toString es un método de la clase Object, el cual es heredado, como sabrás, por todas las clases. Y al instanciarlas, por todos los objetos que puedas fabricar con java.
Algunas clases sobre-escriben este método para incluir los valores de las distintas variables de clase. Pero si no son sobre-escritas, lo que devuelve el método toString, es la clase del objeto seguido de una arroba y el código hascode del objeto. El código hascode es un código identificador de la posición de memoria en la que se almacena el objeto.
Para sobre-escribir el método toString debes de hacerlo mediante un método público, que devuelva un String y cuyo nombre sea toString, sin parámetros.
public String toString(){
  return "Cualquier String procedente de valor como esta cadena de texto
  o procedente de variables String o casteadas a String";
}

Y luego ya depende de qué es lo que quieras que te de el mensaje. Si quieres que te de el nombre del objeto que generó el evento, o alguna de sus propiedades... pues tendrás que acceder a esa propiedad e introducirla en el return. Como no indicas tampoco qué es lo que quieres sacar exactamente, no te puedo ayudar más.
También puedes hacer un return según alguna condición, como por ejemplo, si fue un botón sacar un mensaje, si fue un textField sacar otro mensaje... a saber qué es lo que quieres sacar exactamente.


text:
Q: Search and replace data in google spreadsheet Why doesn't my script work? It doesn't search data. Message shows it done but sheets look like no changing. Who can me help?
function SearchReplaceInFormula() { //begin work

 var pattern = Browser.inputBox("Enter the search string:"); //text on label
 var replacement = Browser.inputBox("Enter the replacement string:"); //text on label
  if (pattern == "" && replacement == "") // empty
 {
 Browser.msgBox("Nothing to search and or replace");
 return;
  }
//
  var formula = SpreadsheetApp.getActiveRange().getValues(); //get a data all range
  var range = SpreadsheetApp.getActiveRange(); //get range
  var crows = range.getNumRows(); //last rows
  var ccols = range.getNumColumns(); //last columns
  var row = 0; //
  for (row = 1; row <= crows; row++)//
  {
  for (col=1; col <= ccols; col++) //
  {
 var cell = range.getCell(row, col);
 var formula = cell.getValues(); //may be getValue
 var updated = formula; //update
 while(-1 != updated.indexOf(pattern)) //what -1
 {
   updated = updated.replace(pattern, replacement); //replace before update
 }
 if (formula != updated)
 {
   cell.setFormula(updated) //set vales?
 }
  }
 }
  Browser.msgBox("Done replacing " + pattern + " with " + replacement); //shows always
  }

A: I've re-worked your code and added a menu option, so that it can be easily accessible.
UPDATE: 09-01-2013
Added extra piece of code to check whether something was changed (array comparison).
Also included a working example of the spreadsheet: Search and replace data in google spreadsheet
function onOpen() {
  // get active spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // create menu
  var menu = [{name: "Searh/Replace", functionName: "SearchReplaceInFormula"}];

  // add to menu
  ss.addMenu("Extra's", menu);
}

function SearchReplaceInFormula() {
  // set parameters
  var pattern = Browser.inputBox("Enter search string:");
  var replacement = Browser.inputBox("Enter replacement string:");

  // inform user if nothing was entered
  if(pattern == "" && replacement == "") {
    Browser.msgBox("Nothing to search and or replace");
    return;
  }

  // get ranges and data
  var dataRange = SpreadsheetApp.getActiveRange().getValues();
  var copyRange = dataRange;
  var range = SpreadsheetApp.getActiveRange();
  var ccols = dataRange[0].length, crows = dataRange.length;

  // itterate through data
  for (var i=0; i<crows; i++) {
    for (var j=0; j<ccols; j++) {
      if(copyRange[i][j].indexOf(pattern) != -1) {
        copyRange[i][j] = copyRange[i][j].replace(pattern, replacement);
      }
    }
  }

  // set changed values
  range.setValues(dataRange);

  // check if array's are equal
  var equal = arraysEqual(copyRange, dataRange);

  // inform user what happend
  if(equal == true) {
    Browser.msgBox("No matches found...");
  } else {
    Browser.msgBox("Done replacing " + pattern + " with " + replacement);
  }
}

function arraysEqual(arr1, arr2) {
  if(arr1.length !== arr2.length)
    return false;

  for(var i = arr1.length; i--;) {
    if(arr1[i] !== arr2[i])
      return false;
  }
  return true;
}


text:
Q: How to do you make colored bullet points with python-docx? I am wondering if it is possible to set the bullet point color in python-docx  (style= List Bullet) without changing the font color?
I know its possible using word but I can't find the attribute to do this via code.
Thanks


text:
Q: Where are registered servers stored? I'm using SMS 2008 & I'm looking for where the registered servers are stored on my local machine.  I have searched the registry with no luck.

A: They are kept as an XML document here:

%APPDATA%\Microsoft\Microsoft SQL Server\100\Tools\Shell\RegSrvr.xml

On Windows XP this resolves to:

C:\Documents and Settings\username\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell\RegSrvr.xml

Note: As of Windows Vista there is no Application Data folder, and the path resolves differently.

A: For Windows 10 and SSMS version V17 the document can be found using this path in windows explorer
%APPDATA%\Microsoft\SQL Server Management Studio

Or this powershell command
dir "$env:APPDATA\Microsoft\SQL Server Management Studio\RegSrvr.xml"

    Example
    Directory: C:\Users\george\AppData\Roaming\Microsoft\SQL Server Management Studio

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       19/02/2019   4:04 PM          60998 RegSrvr.xml

A: In windows 8 and 7 here is the correct path.
C:\Users\username\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\RegSrvr.xml


text:
Q: Javascript loop will not update itself This code does not seem to run well: http://jsfiddle.net/5GEru/1/
var left = 0;
function mouvement(){
    var bouger = document.getElementById("bouge");
    bouger.style.left= left;
    left++;

    mouvement();

}
window.onload = mouvement();

The variable increments itself but somehow the left value does not get reapplied everytime the function is run. it remains at the initial 0.
What am I doing wrong?
Thanks for your tips guys!

A: You're confusing the browser with invalid CSS. The browser is looking for a unit.
Try:
bouger.style.left = left + "px";

A: You need to add "px" to left.
bouger.style.left= left + "px";

Of course, it also runs so fast you can't see anything happen, so I have a modified version:
http://jsfiddle.net/5GEru/2/
Also, your code should terminate at some point. Like when left becomes greater than SOMETHING for example. If you're using jQuery of course, you could just do:
$(function(){
    $("#bouge").animate({"left": 500},2000);
});

See: http://jsfiddle.net/5GEru/6/

A: Use setInterval() to executes a function, over and over again,
Here's your updated code which uses setInterval(), http://jsfiddle.net/5GEru/4/
Also you need to add px in this line, bouger.style.left= left+'px';


text:
Q: Create Unix Named Socket from the Command Line Is there a command similar to mkfifo but for domain sockets?

A: There is no exact equivalent of mkfifo for socket, i.e. there is no command that just creates a "hanging" socket. This is for historical reason: server's function bind(), the one that creates a socket name/inode in the filesystem, fails if the name is already used. In other words, server cannot operate on a pre-existing socket.
So if you'd created socket earlier, it would need to be removed by the server anyway first. No benefit. As you see with Gregory's answer, you can create a socket IF you keep a server for it, such as netcat. Once a server is gone, the old socket is gone. A new server has a new socket, and all clients need to re-connect, despite the socket's name being identical.

A: Most recent netcat (nc) and similar programs (socat as far as I know) have domain socket options.
Else, you can have a look at ucspi-unix

A: You can use python:
python -c "import socket as s; sock = s.socket(s.AF_UNIX); sock.bind('/tmp/test.sock')"

Also C, see this answer.

A: I simply use netcat and stay listening in such a case:
nc -lkU aSocket.sock

you should use netcat-openbsd. netcat-traditional does not have -U switch which is for Unix Domain socket.


text:
Q: speech recognition python code not working I am running the following code in Python 2.7 with pyAudio installed.
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:                # use the default microphone as the audio source
    audio = r.listen(source)                   # listen for the first phrase and extract it into audio data

try:
    print("You said " + r.recognize(audio))    # recognize speech using Google Speech Recognition
except LookupError:                           # speech is unintelligible
    print("Could not understand audio")

The output gives a blinking pointer. That's it.

A: I have solved the same problem for me with the following (noise suppression),
The "listen" function has problems with environment noise. So the running code is only blinking waiting.
Use this ambient noise suppression/adjustment;
    r.adjust_for_ambient_noise(source, duration=5)
Referance

Tuesday, March 28, 2017
Easy Speech Recognition in Python with PyAudio and Pocketsphinx

A: try to add
r.adjust_for_ambient_noise(source,duration=1)

where r is recogniser instance, like this
import speech_recognition as sr

r=sr.Recognizer()
print(sr.Microphone.list_microphone_names())
with sr.Microphone() as source:
    r.adjust_for_ambient_noise(source,duration=1)
    # r.energy_threshold()
    print("say anything : ")
    audio= r.listen(source)
    try:
        text = r.recognize_google(audio)
        print(text)
    except:
        print("sorry, could not recognise")

A: have you tried replacing
    print("You said " + r.recognize(audio))
    except LookupError:
    print("Could not understand audio")

with
    text = r.recognize_google(audio)
    print("You said : {}".format(text))
    text = r.recognize_google(audio)
    except:
        print("Sorry could not recognize your voice")

ensure pyaudio.h is installed by running the below command
    sudo apt-get install portaudio19-dev python-pyaudio python3-pyaudio

A: just try;
pip install sounddevice

it works.

A: check the input volume of your microphone. It is by default set to 0 in ubuntu (in my case). Since your program got stuck on the line audio = r.listen(source), which simply means that the microphone is not able to listen to any voice input. Hope this helps.

A: try this code:
r = sr.Recognizer()

with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source=source)
        audio = r.listen(source,timeout=3)

    data = ''
    try :
        data = r.recognize_google(audio)
        print(data)

    except sr.UnknownValueError:
        print(" Error")

    except sr.RequestError as e:
        print("Request Error")

or add timeout and r.adjust_for_ambient_noise(source=source) to your code as above.please can anyone help me with this

A: The possible reason could be that the recognizer_instance.energy_threshold property is probably set to a value that is too high to start off with. You should decrease this threshold, or call recognizer_instance.adjust_for_ambient_noise(source, duration = 1). You can learn more about it at Speech Recognition

A: In addition to Tushar's answer, I suggest trying a nicer external USB microphone. PyAudio can have issues with a simple  built-in laptop microphone.

A: You may have to install these things first:

*

*pip install pyaudio

*pip install --upgrade pyaudio

*pip install wheel

*pip install google-api-python-client

*sudo apt-get install flac

*pip install monotonic

*pip install SpeechRecognition

After that, refer the site (https://realpython.com/python-speech-recognition/)
it will clearly explain what you wanted.

Here I am attaching the code I've edited from that site. Since I am new it will not be perfect, but I've tried. This is to check weather the voice input is similar to the text I've given and also it will print what you said.

#!/usr/bin/ python
import time

import speech_recognition as sr

def recognize_speech_from_mic(recognizer, microphone):
    """Transcribe speech from recorded from `microphone`.

    Returns a dictionary with three keys:
    "success": a boolean indicating whether or not the API request was
           successful
    "error":   `None` if no error occured, otherwise a string containing
           an error message if the API could not be reached or
           speech was unrecognizable
    "transcription": `None` if speech could not be transcribed,
           otherwise a string containing the transcribed text
    """
    # check that recognizer and microphone arguments are appropriate type
    if not isinstance(recognizer, sr.Recognizer):
        raise TypeError("`recognizer` must be `Recognizer` instance")

    if not isinstance(microphone, sr.Microphone):
        raise TypeError("`microphone` must be `Microphone` instance")

    # adjust the recognizer sensitivity to ambient noise and record audio
    # from the microphone
    with microphone as source:
        recognizer.adjust_for_ambient_noise(source)
        audio = recognizer.listen(source)

    # set up the response object
    response = {
        "success": True,
        "error": None,
        "transcription": None
    }

    try:
        response["transcription"] =    recognizer.recognize_google(audio)
    except sr.RequestError:
        # API was unreachable or unresponsive
        response["success"] = False
        response["error"] = "API unavailable"
    except sr.UnknownValueError:
        # speech was unintelligible
        response["error"] = "Unable to recognize speech"

    return response

if __name__ == "__main__":

    NUM_GUESSES = 1
    PROMPT_LIMIT = 2
    # create recognizer and mic instances
    recognizer = sr.Recognizer()
    microphone = sr.Microphone()

    word = "hello world"

    time.sleep(3)

    for i in range(NUM_GUESSES):
        for j in range(PROMPT_LIMIT):
            print('Guess {}. Speak!'.format(i+1))
            guess = recognize_speech_from_mic(recognizer, microphone)
            if guess["transcription"]:
                break
            if not guess["success"]:
                break
            print("I didn't catch that")

        # if there was an error, stop the game
        if guess["error"]:
            print("ERROR: {}".format(guess["error"]))
            break

        # show the user the transcription
        print("You said: {}".format(guess["transcription"]))

        # determine if guess is correct and if any attempts remain
        guess_is_correct = guess["transcription"].lower() == word.lower()
        user_has_more_attempts = i < NUM_GUESSES - 1

        if guess_is_correct:
            print("Correct!".format(word))
            break
        elif user_has_more_attempts:
            print("Incorrect. Try again.\n")
        else:
            print("Sorry, output is not similar to '{}'.".format(word))
            break

A: MY Problem was : the program is running without any error but its not showing any output
THIS IS THE CODE WITH PROBLEM:
import googletrans
import speech_recognition as sr

recognizer = sr.Recognizer()
translator = googletrans.Translator()

try:
    with sr.Microphone() as source:
        print('Speak Now')
        voice= recognizer.listen(source)
        text= recognizer.recognize_google(voice)
        print(text)

except:
     pass

translated = translator.translate(text, dest='es')
print(translated.text)

To Solve this problem :
basically this problem occurs by the background noise or ambient noise
SO just add only one line to your code which is :
recognizer.adjust_for_ambient_noise(source)#recognizer is on line 4 from above code
########
The improved and Solved problem code:
########
import googletrans
import speech_recognition as sr

recognizer = sr.Recognizer()
translator = googletrans.Translator()

try:
    with sr.Microphone() as source:
        print('Speak Now')
        recognizer.adjust_for_ambient_noise(source)#(Problem Solved)
        voice= recognizer.listen(source)
        text= recognizer.recognize_google(voice)
        print(text)

except:
     pass

translated = translator.translate(text, dest='es')
print(translated.text)

A: Put the Try and Except inside the indentation.
Here is my Working code:-
while True:
    r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Say Something")
            audio=r.listen(source)
        try:
            print(r.recognize_google(audio),"\n")
        except:
            pass

A: I guess the problem is with the duration. If you set some duration to the speech recognition engine the problem will be resolved.
Try the following code:

import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
    speak(sen)
    print("listening...")
    audio = r.record(source,duration=3)
    try:
        str=r.recognize_google(audio)
        print(str)
    except:
        print("some error occurred!")

A: Please set minimum threshold.
After running commend python -m speech_recognition. Set minimum energy threshold which it display.
Setting procedure: press Ctrl then click mouse Recognizer(). Now set energy threshold.

A: Install in your python prompt (Anaconda Prompt)

*

*pip install pyaudio

*pip install --upgrade pyaudio

*pip install wheel

*pip install google-api-python-client

*pip install monotonic

*pip install SpeechRecognition

Code:
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
    print("listening...")
    audio = r.record(source,duration=3)
    try:
        str=r.recognize_google(audio)
        print(str)
    except:
        print("some error occurred!")

A: Try changing the mic index using:
with sr.Microphone(device_index = 0) as source:

To know your mic index use:
print((sr.Microphone.list_microphone_names()))

If this does not work use:
with sr.Microphone(device_index = 0) as source:                # use the default microphone as the audio source
   r.adjust_for_ambient_noise(source, duration = 1)
   audio = r.listen(source)


text:
Q: Problema con mostrar valores en una tabla Javascript Tengo el siguiente código que me genera una tabla a partir de unos datos que llegan de un arreglo, el código me muestra los valores de cada producto por semana y su total de la siguiente manera:
-----------------------------------------------------
Land     |     Product   |    25   |    26   | Total |
-----------------------------------------------------
FINCA1   |     ROSA      |   2000  |   1254  |  3254 |
-----------------------------------------------------
FINCA2   |     ROSA      |   1900  |   123   |  2023 |
-----------------------------------------------------
FINCA3   |     ROSA      |   350   |   200   |  550  |
-----------------------------------------------------
FINCA3   |     ROSA1     |   410   |    0    |  410  |
-----------------------------------------------------
TOTAL    |               |   4660  |   1577  |  6237 |
------------------------------------------------------

var data = [
  {id:1, land: 'FINCA1',  product: "ROSA", week:25,  quantity: 2000},
  {id:1, land: 'FINCA2',  product: "ROSA", week:25, quantity: 1900},
  {id:1, land: 'FINCA3',  product: "ROSA", week:25, quantity: 350},
  {id:1, land: 'FINCA3',  product: "ROSA1",week:25, quantity: 410},
  {id:1, land: 'FINCA1',  product: "ROSA", week:26, quantity: 1254},
  {id:1, land: 'FINCA2' ,  product: "ROSA",week:26, quantity: 123},
  {id:1, land: 'FINCA3' ,  product: "ROSA",week:26, quantity: 200}
];

//Obtengo los keys del objeto para crear el Thead de la tabla y los guardo en una variable

var tabla = document.createElement('table');
var tableHead = document.createElement('tr');

Object.keys(data[0]).forEach(prop=>{
  if(prop != 'week' && prop != 'quantity')
  tableHead.innerHTML += ''+prop+'	';
});

var semanas = data.reduce( (semanas_, elemento)=>{
  if(semanas_.indexOf(elemento.week) == -1)
    semanas_.push(elemento.week)
  return semanas_;
}, []);

semanas.forEach( semana=>{
  tableHead.innerHTML += ''+semana+'	';
});

var total_semanas = [];

tableHead.innerHTML += 'Total	';
tabla.appendChild(tableHead);

var tbody = document.createElement('tbody');

tabla.appendChild(tbody);

document.querySelector('body').appendChild(tabla);

var arrayOrganizado = data.reduce((arr, item)=>{

  var t = total_semanas.find(e=> e.semana === item.week);
  if (t) t.total += item.quantity;
  else total_semanas.push({ semana : item.week, total : item.quantity });

  item.week = {
    numero : item.week,
    cantidad : item.quantity
  }
  var ele = arr.find(it=>it.land === item.land && it.product === item.product);
  if(ele){
    ele.week.push(item.week);
    ele.total = ele.week.reduce((a, b)=> a + b.cantidad, 0);
  } else {
    item.week = [item.week];
    item.total = item.quantity;
    arr.push(item);
  }
  return arr;
}, []);

arrayOrganizado.forEach(fila=>{
  var f = Object.keys(fila).reduce( (a, b)=>{
    //console.log(b);
    if(b != 'week' && b != 'quantity' && b != 'total')
      return a +  '' + fila[b] + '	';
    return a;
  }, '');
  tbody.innerHTML += f + semanas.reduce( (a, _, i)=>a + '' + (fila.week[i] ? fila.week[i].cantidad : 0) + '	', '') + '' + fila.total + '	';
});

var f = Object.keys(arrayOrganizado[0]).reduce( (a, b)=>{
  //console.log(b);
  if(b != 'week' && b != 'quantity' && b != 'total')
    return a +  ' ---- 	';
  return a;
}, '');

tbody.innerHTML += f + total_semanas.reduce( (a, _, i)=>a + '' + _.total + '	', '') + '' + total_semanas.reduce( (a, b) => a.total + b.total) + '	';

Hasta aquí todo esta bien, el problema es que cuando se aumentan las semanas, pueden haber semanas que no tengan valores y su resultado es 0, pero en lugar de poner ese valor en la semana que corresponde lo pone en la última, me explico:
El arreglo puede llegar de la siguiente manera
var data = [
      {id:1, land: 'FINCA1',  product: "ROSA", week:25,  quantity: 2000},
      {id:1, land: 'FINCA2',  product: "ROSA", week:25, quantity: 1900},
      {id:1, land: 'FINCA3',  product: "ROSA", week:25, quantity: 350},
      {id:1, land: 'FINCA3',  product: "ROSA1",week:25, quantity: 410},
      {id:1, land: 'FINCA1',  product: "ROSA", week:26, quantity: 1254},
      {id:1, land: 'FINCA2' , product: "ROSA", week:26, quantity: 123},
      {id:1, land: 'FINCA3' , product: "ROSA", week:26, quantity: 200},
      {id:1, land: 'FINCA3' , product: "ROSA", week:24, quantity: 200}
      {id:1, land: 'FINCA3' , product: "ROSA", week:23, quantity: 1200}
    ];

La tabla debería quedar así:
-----------------------------------------------------------------------
Land     |     Product   |    23   |    24   |   25  |  26  |   Total |
-----------------------------------------------------------------------
FINCA1   |     ROSA      |   0     |   0     |  2000 | 1254 |  3254   |
-----------------------------------------------------------------------
FINCA2   |     ROSA      |   0     |   0     |  1900 | 123  |  2023   |
-----------------------------------------------------------------------
FINCA3   |     ROSA      |   1200  |   200   |  350  | 200  |  1950   |
-----------------------------------------------------------------------
FINCA3   |     ROSA1     |   0     |    0    |  410  |   0  |  410    |
-----------------------------------------------------------------------
TOTAL    |               |   1200  |   200   |  4660 | 1577 |  7637   |
-----------------------------------------------------------------------

Sin embargo, la tabla me queda así;
-----------------------------------------------------------------------
Land     |     Product   |    23   |    24   |   25  |  26  |   Total |
-----------------------------------------------------------------------
FINCA1   |     ROSA      |   2000  |  1254   |  0    | 0    |  3254   |
-----------------------------------------------------------------------
FINCA2   |     ROSA      |   1900  |   123   |  0    | 0    |  2023   |
-----------------------------------------------------------------------
FINCA3   |     ROSA      |   1200  |   200   |  350  | 200  |  1950   |
-----------------------------------------------------------------------
FINCA3   |     ROSA1     |   410   |    0    |    0  |   0  |  410    |
-----------------------------------------------------------------------
TOTAL    |               |   1200  |   200   |  4660 | 1577 |  7637   |
-----------------------------------------------------------------------

Creo que es la función reduce que me genera el problema en esta parte:
tbody.innerHTML += f + semanas.reduce( (a, _, i)=>a + '' + (fila.week[i] ? fila.week[i].cantidad : 0) + '	', '') + '' + fila.total + '	';

No se si haya otra función similiar que haga lo mismo, o no se si es esa función, agradezco su ayuda

A: El problema no está en la función reduce sino en el ordenamiento de los datos y la inclusión de los datos Ausentes. No indagué mucho en el codigo ni pretendo hacerle mejoras, solo solucioné los errores que generaban que los datos se mostraran en las columnas incorrectas.

*

*No se ordenan los datos: si se quiere mostrar el numero de la semana por orden, siempre es necesario ordenarlos en algun punto. en el ejemplo que tienes, las semanas quedan ordenadas en la siguiente forma:
25 | 26 | 24 | 23
Las semanas quedan en el mismo orden en el que se presentan en el arreglo llamado data. por lo que se puede aplicar sort en el arreglo semanas para que por lo menos la cabecera quede bien.
var semanas = data.reduce( (semanas_, elemento)=>{
  if(semanas_.indexOf(elemento.week) == -1)
    semanas_.push(elemento.week)
  semanas_.sort();
  return semanas_;
}, []);

*La información en cada fila se encuentra indexada incorrectamente, por ejemplo si en total se tienen 7 semanas, pero cada file tiene 2, 3 o 4 semanas, en la forma en que se estaba indexando siempre se mostrara la información en las primeras columnas de la fila y las demás se rellenarán con ceros. Hay muchas formas de hacerlo, una puede ser insertar en cada fila valores que representen las semanas faltantes, yo elegí al momento de mostrar cada celda, comprobar si existe esa semana para la fila actual, si existe mostrar el valor, poner cero sí no.

La diferencia entre los dos métodos depende mas del rendimiento esperado, pero para la mayoría de los casos no hay grandes penalidades en tiempo de ejecución.
tbody.innerHTML += f + semanas.reduce( function(a, c, i){
        var w = fila.week.find(function(current,index,fila_weeks){
        return current.numero===c;
            });
          if (w===undefined){
            w=0;
          }else{
            w=w.cantidad;
          }
        return a + '' + w + '	'},   '') + '' + fila.total + '	';
});

Edit: se añade el ordenamiento a la fila de totales.
El código completo lo puedes probar en este jsfiddle.


text:
Q: implementing twitter bootstrap menu in joomla bootstrap template I am making a responsive twitter bootstrap template for joomla 2.5/3.x versions.
But problem is  implementing top menu of joomla. I have a menu in joomla, with some menu items has sub menu items, so when mouse is placed on any item, those sub menu items will be shown normally.
I've tried this code in my template -

        <div class="container<?php echo $template_width; ?>">
            <?php if($this->countModules('top-nav')) : ?>

            <?php endif; ?>
            <?php echo $custom_logo; ?>
            <?php if($this->countModules('top-nav')) : ?>

                <jdoc:include type="modules" name="top-nav" style="none" />

            <?php endif; ?>

As you see, when I place my joomla menu from module manager to "top-nav" position, that menu will be displayed at top of template.
But it does show menu as well as sub menu items for some menu items, which is not expected as I want those sub menu items of main menu item will be hidden and will be displayed on mouse over. I saw in bootstrap tutorials this way things works well but not in my case.
So please help with examples to make navigation menu work. Also I used bootstrap 2.3.2 version as latest bootstrap 3.0.0 version even does not show menu.
Also my another concern is joomla 3.x already have bootstrap, so it looks like I will have to include only those existing instead of the way I include bootstrap in joomla 2.5 versions.
In this case how do I ensure compatibility of my template for both joomla 2.5 and 3 versions? as in template I using bootstrap 2.3.2 version for joomla 2.5 versions.

A: Consider using the JS_WRIGHT template framework. All of those issues and a lot more are already worked out for you. See: https://github.com/joomlashack/wright


text:
Q: Nginx: proxy pass with basic http auth and excluding some files I'm trying to exclude some files from http auth (Brightcove video upload fix in Drupal), but my nginx configuration doesn't work properly:
location / {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;

location ~* \.(3g2|3gp|asf|avi|dv|flv|f4v|m4v|mov|mp4|mpeg|mpg|mts|m2ts|qt|wmv|jpg|png|jpeg)$ {
    auth_basic off;
    allow all;
}

proxy_set_header Authorization  "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass $ip;
}

Http auth is working, proxy pass is working but I'm still not able to upload Brightcove videos. Similar config for another server with apache worked fine:
AuthType Basic
AuthName "Protected Area"
AuthUserFile /etc/.htpasswd
Require valid-user
SetEnvIf REQUEST_URI \.(3g2|3gp|asf|avi|dv|flv|f4v|m4v|mov|mp4|mpeg|mpg|mts|m2ts|qt|wmv|jpg|png|jpeg)$ allow
AllowOverride All
Order deny,allow
Deny from all
Allow from env=allow
Satisfy any

Does anyone can help me with this?
Thanks!

A: this is what worked fine:
location / {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
    proxy_set_header Authorization  "";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass $ip;
}

location ~* \.(3g2|3gp|asf|avi|dv|flv|f4v|m4v|mov|mp4|mpeg|mpg|mts|m2ts|qt|wmv|jpg|png|jpeg)$ {
    auth_basic off;
    allow all;
    proxy_set_header Authorization  "";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass $ip;
}

I tested this config before, but didn't know that Brightcove videos need some time to start playing :-)


text:
Q: How can I send JSON to consumer using RabbitMQ and Elixir? I am trying to send JSON to consumer with RabbitMQ? Is it possible and how? I am using Elixir as my programming language.

A: Follow this link to :
https://github.com/pma/amqp
Open issues to more information about send JSON.
iex(1)> {:ok, conn} = AMQP.Connection.open
{:ok, %AMQP.Connection{pid: #PID<0.364.0>}}
iex(2)> {:ok, chan} = AMQP.Channel.open(conn)
{:ok,
 %AMQP.Channel{conn: %AMQP.Connection{pid: #PID<0.364.0>}, pid: #PID<0.376.0>}}
iex(3)> AMQP.Queue.declare chan, "test_queue"
{:ok, %{consumer_count: 0, message_count: 0, queue: "test_queue"}}
iex(4)> AMQP.Exchange.declare chan, "test_exchange"
:ok
iex(5)> AMQP.Queue.bind chan, "test_queue", "test_exchange"
:ok
iex(6)> AMQP.Basic.publish(chan, "test_exchange", "", Poison.encode(%{ name: "S" }), [content_type: "application/json"])
:ok


text:
Q: c -lz library link order (undefined reference to symbol "inflateInit2_") I link the the library in CodeBlocks in this order,
-lz
-L/usr/local/lib
-L/usr/local/include
-pthread
-lswscale
-lavutil
-lavcodec
-lmp3lame
-lopus
-ltiff
-lvorbis
-ltheora
-ltheoraenc
-ltheoradec
-lvorbisenc
-ltiffxx
-llzma
-lva
-lavfilter
-lavformat
-lfreetype

still got error:
undefined reference to symbol "inflateInit2_"

I am wondering whether it is the library link order problem?
Where should I put the -lz?

A: For GCC and Clang (and probably e.g. the Intel compiler too) the rule is that references from earlier on in the command line are satisfied from libraries specified later on in the command line.
For example, if foo.c references functions from the library bar, then it's correct to compile with
$ gcc foo.c -lbar

, and incorrect to compile with
$ gcc -lbar foo.c

Therefore, your safest bet would be to put -lz last, so that it can satisfy reference from all the libraries specified earlier.
Here's a relevant quote from the gcc(1) man page (-l option):

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified.  Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o.  If bar.o refers to functions in z, those functions may not be loaded.

However, even better might be to use e.g. pkg-config(1) with --libs to get the flags you need for a particular library. Some libraries also ship with custom scripts for this purpose (e.g., sdl(2)-config for SDL(2)).


text:
Q: How can I fix the problem that appears when I enter npm i in the console. I am using gulp PS C:\Users\user1\Desktop\hello> npm i

npm WARN deprecated gulp-util@3.0.8: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5

npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.

npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated phantomjs-prebuilt@2.1.16: this package is now deprecated
npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated mkdirp@0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules\chokidar\node_modules\fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
-
npm ERR! code ENOENT
-
npm ERR! syscall spawn git
-
npm ERR! path git
-
npm ERR! errno ENOENT
-
npm ERR! enoent Error while executing:
-
npm ERR! enoent undefined ls-remote -h -t ssh://git@github.com/DABH/diagnostics.git
-
npm ERR! enoent

npm ERR! enoent
-
npm ERR! enoent spawn git ENOENT
-
npm ERR! enoent This is related to npm not being able to find a file.
-
npm ERR! enoent
-
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user1\AppData\Roaming\npm-cache\_logs\2020-06-22T15_12_17_615Z-debug.log

A: It seems to be related to recent changes on the package.
See : https://github.com/3rd-Eden/diagnostics/issues/22

A: Is git installed? I think a downstream package dependency recently changed to require that ssh://git@github.com/DABH/diagnostics.git


text:
Q: Chef: should I be checking "syntaxcache" files into version control? I'm learning Chef and am keeping my chef-repo in version control. When I use knife cookbook upload and then run git status I see a bunch of new files in .chef/syntaxcache. They look like this:
.chef/syntaxcache/8ab66bdf1ceb07273f7b3d71f483fbd84be595e845e90ffcbeb0ba6d22f684b0
Should I be adding these to version control or just put a pattern in .gitignore to leave them out?

A: No, most stuff under .chef are temp files. Specifically those are (I think) rendered versions of Erb templates so we can run a Ruby syntax checker on them. I'm kind of surprised we don't delete them afterwards though, that's probably a bug.


text:
Q: Cannot configure Apache to parse PHP files I have installed xampp in linux. And then I have updated the php.ini file like removed the ; before some libraries.
If i type localhost/test.php then that php file is downloading instead of execution.
https://stackoverflow.com/questions/12893714/installed-xampp-on-linux-but-it-now-just-downloads-php-files-instead-of-displa
The problem associated with the above url is same. I have tried the solutions for the above problem.But did not get solved.
Any body can help me.
thanks

A: First be sure that you have installed libapache2-mod-php5, if you are using ubuntu, open a terminal and go to /etc/apache2/mod-available and locate php5.conf and php5.load
If you dont have this module you cant load php files. You can check this page https://help.ubuntu.com/12.10/serverguide/php5.html


text:
Q: DevExpress XtraTabControl HeaderOrientation is not working Dears,
I have WinForms application and I need to change XtraTabControl1's HeaderOrientation to Horizontal. Even it works design time, but runtime it isis displayed as Vertical. However, in the same application in different Form it works as expected. Could you pls help on this?
Thanks.

A: I found the problem: If you use below options of XtraTabControl, then problem is raising:
private void button1_Click(object sender, EventArgs e)
        {
            this.xtraTabControl1.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Flat;
            this.xtraTabControl1.LookAndFeel.UseDefaultLookAndFeel = false;
        }

Thanks.


text:
Q: Trying to fill Hexagon shape with color I'm drawing a 2d grid of hexagons using the DrawPolygon function.  Works great, but I'm trying to figure out how to fill them with a certain color.  It would appear the FillEllipse function is only meant for rectangles.  Is there something I could use to fill shapes made with DrawPolygon?  Please note, the below code includes a function I'm too lazy to include called CreateHex, which passes 2 coordinates (x and y of course) which it uses to calculate the 6 points which CreateHex uses to return the 6 points needed for the Hexagon.  Here's my code:
    Dim myPen As New Pen(Color.Black)
    Dim PicGraphics As Graphics = Graphics.FromImage(bmp)
    Dim DrawFont As New Font("Arial", SizeSide / 3)
    Dim drawFormat As New StringFormat
    Dim drawBrush As New SolidBrush(Color.Black)
    For lc = 1 To ColNum
        For lc2 = 1 To RowNum
            PicGraphics.DrawPolygon(myPen, CreateHex(lc, lc2))
            PicGraphics.FillEllipse(New SolidBrush(Color.Red), CreateHex(lc, lc2)) ' <---- this doesn't work.
        Next
    Next

If I comment out the FillEllipse statement, it draws the polygons normally.  But if its uncommented, it will draw nothing at all.  Anyone know of a solution?


text:
Q: Making SQL and R cells always run together in R Notebook R notebooks allow us to write SQL code directly with a dedicated chunk defined by {sql}. However, that call isn't very useful until we get its output and process it in the next R chunk:
```{sql output.var="data"}
SELECT * FROM foo
```

```{r}
dt = data.table(data)
# do stuff with the data
```

Is there a way to bind such chunks together, so that running one automatically runs the other as well? Even better, can it be one-way (such that running the SQL automatically calls the R block, but running the R block doesn't run the SQL)?
To clarify, I'd like to know if it's possible to do something like
```{sql output.var="data" runNextChunk=TRUE}
SELECT * FROM foo
```

Or perhaps
```{sql output.var="data" runAfter="bar"}
SELECT * FROM foo
```

```{r name="bar"}
dt = data.table(data)
# do stuff with the data
```

Obviously, once the notebook is complete, I can knit it and all the cells will be processed. However, while developing I often find myself making adjustments to my SQL call and then having to move the caret to the next chunk and runing it as well.
I've looked at the R Markdown docs, but haven't found anything like this, so here's to hoping I just missed it.


text:
Q: copying a directory files into current directory If I have a directory "test" and inside a directory "new" and I want to copy all files from "new" to test(my current directory).
I tried: cp -r new . because I know dot is like current directory but it didn't work.

A: Assuming you are in "test":
cp -r new/* .
To test:
mkdir test
cd test
mkdir new
touch new/1
touch new/2
touch new/3
cp -r new/* .

Output:
$ ls
1  2  3  new

A: This will do it:
     cp -rf present/directory /desire/directory


text:
Q: Preposition to follow "Further acknowledgment"? I have a statement. And after that statement I have:

This is further acknowledged by the
  consolidation of the material.

But I want to remove the "This". What preposition can I use here:

Further acknowledgement arrives from
  the consolidation of the material.

.
I'm not sure if "arrives" should is correct or formal enough. This is for a PhD thesis.

A: You could say

We receive further acknowledgement from the consolidation of the material.

or

Further acknowledgement comes from the consolidation of the material.

or

The consolidation of the material constitutes further acknowledgement.

and so on.
I too wonder, as does @RegDwight, why the demonstrative pronoun this bothers you so much? I find this very puzzling, as this is not only common and clear but allows for more succinct referencing of subjects than other constructions might. The only time it becomes difficult to parse is when the antecedent is unclear (e.g., when it is the subject of a clause or sentence which might refer to multiple subjects from a previous clause or sentence).

A: Slightly less verbose:

Further acknowledgement follows the consolidation of the material.

or, slightly more precise:

Further acknowledgement results from consolidation of the material.

Side note: I hope that your context answers the questions: "Acknowledgement of what?" and "What material?".


text:
Q: How to download file from tomcat server by javascript? I saved a text file in my Tomcat folder,
c:\program files/apache software foundation/tomcat7.0/test/test.txt
I can only open it in the browser on my own PC.
How can I download and save it to my local disk,for example: f:\test.txt.
Can I use Javascript only?
Any sample code?
Thanks a million!

A: All webserver support ajax. You can try ajax from your local webserver only.  To upload to a server you need to buy domain name and webspace. Contact any webhosting company, they will guide you, for eg: http://godaddy.com/. Below is the ajax code to read text file from your server
 var txtFile = new XMLHttpRequest();
    txtFile.open("GET", "http://www.example.com/data/data.txt", true);
    txtFile.onreadystatechange = function() {
      if (txtFile.readyState === 4) {  // Makes sure the document is ready to parse.
        if (txtFile.status === 200) {  // Makes sure it's found the file.
          allText = txtFile.responseText;
          lines = txtFile.responseText.split("\n"); // Will separate each line into an array
        }
      }
    }
    txtFile.send(null);


text:
Q: Linker Error LNK2019 I have been playing around with Template functions, and made a little logger program. I have been trying to split this into header / source file, but I keep getting linker errors. I know this is simple, but I cant figure it out.
Also I have some convince vars in the logger header, where would be the "proper" place for those? (logStart, logEnd etc.)
All code below.
Header
#ifndef __moot_logger_hpp__
#define __moot_logger_hpp__

#include <iostream>
#include <fstream>
#include <string>

using std::ios;

namespace Moot
{
    struct Logger
    {
        Logger();
        ~Logger() {}

        template <class T>
        void saveToFile(T type);

        template <typename T>
        Logger& operator<< (T type);

        /*
        Logger& operator<< (std::wstring wideStr)
        {
            saveToFile(Moot::convertWstringToString(wideStr));
            return *this;
        }
        */
    };

    /*
    namespace {
        Logger logStart;
        Logger& lStart = logStart;

        const char  logEnd = '\n';
        const char& lEnd   = logEnd;

        const char  logSpace = ' ';
        const char& lSpace   = logSpace;
    }
    */

}

#endif

Source
#include <Moot/logger.hpp>

Moot::Logger::Logger()
{
    std::ofstream logfile;
    logfile.open ("logfile.txt", ios::trunc);
    logfile << "LogFile - most recent at the bottom\n";
    logfile << "-----------------------------------\n \n";
    logfile.close();
}

template <typename T>
void Moot::Logger::saveToFile(T type)
{
    std::ofstream logfile;
    logfile.open ("logfile.txt", ios::in | ios::app);
    logfile << type;
    logfile.close();
}

template <typename T>
Moot::Logger& Moot::Logger::operator<< (T type)
{
    saveToFile(type);
    return *this;
}

/*
Logger::Logger& operator<< (std::wstring wideStr)
{
    saveToFile(Moot::convertWstringToString(wideStr));
    return *this;
}
*/

main
#include <Moot/logger.hpp>
#include <iostream>

int main()
{
    std::cout << "hello" << std::endl;

    Moot::Logger() << 12;
    //Moot::lStart.saveToFile(23);
    //Moot::lStart.operator << 13;

    return 0;
};

A: You'll want to read the C++ FAQ Lite question, "Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?"
Effectively, you need to define your function and class templates in the header file, not in the .cpp file.

A: If you want divide definition from declaration for template classes than move definition to separate file with hpp or tpp (tpp not always correctly handled by text editors) extension and add include directive for definition file at the end of declaration file


text:
Q: cs50 pset3 - Sorting void sort(int values[], int n)
{
    int swap, i;
    do{
    swap = 0;
    for(i=0; i<n; i++){
        if(values[i]>values[i+1]){
            int temp = values[i+1];
            values[i+1] = values[i];
            values[i+1]=temp;
            swap = 1;
            }printf("%d\n", values[i]);
        }
    }while(swap == 1);
}

it doesn't seem to be working. what could be wrong?
values: 59797 10425 37569 52527 36285
as sorted: 10425 37569 52527 36285 59797
CHANGED IT
void sort(int values[], int n)
{
    int swap, i, temp;
    // TODO: implement an O(n^2) sorting algorithm
    do{
    swap = 0;
    for(i=0; i<n; i++){
        if(values[i]>values[i+1]){
            temp = values[i+1];
            values[i+1] = values[i];
            values[i]=temp;
            swap = 1;
            }
            printf("%d\n", values[i]);
        }
    }while(swap == 1);
}

values: 59797 10425 37569 52527 36285
as sorted: 0
10425
36285
37569
52527

A: Look at these two lines.
 values[i+1] = values[i];
 values[i+1]=temp;

Does it not look like you're setting the same element twice, to two different values, for no effect?
What purpose does the first statement serve? There is your answer.

When i is its last value (n-1), then you will compare values[n-1] with values[n].One of those elements is not in your array.  You just did an out-of-bounds access.

A: I suggest you consider using built in function. qsort may simplify things.


text:
Q: How do you update apis in real time? So I've been looking for tutorials on how to update a RESTful api every day automatically. I want the data to change each day, so is there a way to do this using node.js?
(No code provided because I want to create a new api)


text:
Q: Why does this do while loop repeat infinitely? I want to prompt the user to input an integer, but if the user enters a non-integer, the program should keep demanding an integer until the user complies.
int getInteger(){
    int input;

    do{
        std::cout << "Enter an integer: ";
        std::cin >> input;
    } while(!(std::cin));

    return input;
}

If the user enters an integer, the function returns it.
But if the user enters something like "Hello," the function goes on an infinite, cout-ing "Enter an integer: ".
How do I fix this?

A: !(std::cin)

will evaluate to true if std::cin is in a bad state, e.g. after an input operation failed. Then, all subsequent input operations will fail immediately and not change cin's error state, thus the infinite loop.
To get the behavior you want, you may use something like
while (!(std::cin >> input)) {
    std::cout << "Try again\n";
    // Clear away the error state
    std::cin.clear();
    // Ignore what ever garbage is still in the stream
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

In the real world, you may want to handle the (generally not recoverable) failures eof (someone sent an End of File character) and bad (cin is broken, should not happen) different than fail which happens after invalid input. This is, for example, shown on this reference page for ignore. However, this should not bite you in toy programs like yours seems to be.

A: Streams convert to true while there is none of the failure bits is set. Once a stream entered the failure state, i.e., std::ios_base::failbit (or std::ios_base::badbit) is set for the stream, it stays in that state until the failure bit is cleared using clear(). In addition to clearing the stated you'd also need to get rid of the offending character(s) causing it to get into this state, e.g., using ignore().


text:
Q: Windows asks me for a bluetooth pairing code for my headset I have a Motorola / Sol Republic Tracks Air bluetooth headset. It works fine with both of my phones, and now I'm trying to use it to listen to the audio on my Windows 7 laptop. I have a cheap, unbranded bluetooth receiver bought off Deal Extreme. I know it works, because my girlfriend uses it to send pictures from her phone to her computer.
I coonected the bluetooth receiver on my lapptop and after automatically downloading the drivers off Windows Update, it is detected as "Generic Bluetooth Radio - Cambridge Silicon Radio Ltd." (see image below):

Then I proceed to pair the headset to the computer: as soon as I turn on the headset it enters pairing mode, announced by a series of beeps. If it was my phone I'd just turn on the bluetooth feature, wait for the scan to find the headset, press on its icon and the pairing would be finished. On Windows 7, I right-click on the bluetooth icon on the system tray, select "add a device", click the device name and press "next". It then presents me a dialog asking if I want to set a pairing code to type on the device keyboard, or type on the computer the device pairing code ("look for it on the user manual"), or pair without a code (see images below):

The device (obviously) has no keyboard, and although I have RTFM there is no mention of a pairing code on the user manual, so I choose the latter option. Then almost simultaneously three things happen: (1) a notification that the device has been added to the computer, (2) a driver install dialog showing Windows retrieving the drivers from Windows Update -- the three items installed are "Tracks Air (Mono Audio)", "Tracks Air (Stereo Audio)" and "Tracks Air (Remote Control)" -- and (3) a bubble notification stating "a bluetooth device is trying to connect".

If I click on the bubble notification, I am shown a dialog window asking for the pairing code (see image below). The problem here is, as far as I know of, there's no pairing code!

The headset seems to be recognized by Windows: it shows on the "printers and devices list" on control panel. Below are the "hardware" and "bluetooth" tabs of the device properties. On this last tab it says "device currently connected" even if I turn the headset off. There's also a "services" tab indicating "audio collector", "remote control" and "hands free telephony" (and with "headset" unchecked. I if check it and click "apply", it shows a driver installation dialog, and fails for "Tracks Air (Mono Audio)", but I suppose it is not relevant because I want audio output on the headset only).

Meanwhile, the headset keeps beeping to indicate it's still on pairing mode, and the "a bluetooth device is trying to connect" bubble keeps appearing periodically on the system tray.
The playback devices tab shows the headset as a possible audio output (see image below), but the option to use it as default is greyed out. There is a "connect" option, but upon clicking it, the system tray bubble shows up again.

A: I tried pairing the device on Ubuntu 12.04. Upon clicking on "Add a new device" it shows the following screen; the "PIN Options" button shows a dialog box that allow me to either select some sort of PIN auto configuration or insert a PIN manually.

The same dialog box states that many devices have their default PINs set as 1111, 1234 or 0000; the latter more common for devices such as microphones, mice and GPS.
I have entered 0000 on my device and it paired.