text:
Q: How Do I Remove An Existing Word Doc Watermark With Powershell? I need to use PowerShell to remove a watermark from an existing Word doc. I'm attempting to convert the results of the Word macro recorder to PowerShell but am getting a "[System.__ComObject] doesn't contain a method named 'Shapes'" error. Any help is appreciated. The PS code is below.
$Word=New-Object -ComObject "Word.Application"
$wdSeekPrimaryHeader = 1
$Doc=$Word.Documents.Open("C:\Users\mynamehere\Downloads\andSuch\SampleDoc1.docx")
$Selection=$Word.Selection
$Doc.ActiveWindow.ActivePane.View.SeekView=$wdSeekPrimaryHeader
$Selection.HeaderFooter.Shapes("PowerPlusWaterMarkObject357476642").Select
$Selection.ShapeRange.Delete
$Doc.Save()
$Doc.Close()
$Word.Quit()

A: Show your code?
A simple search for your use case 'PowerShell and Microsoft word remove watermark' would give you a list, and even full scripts for exactly what you are after. For example, this one is about adding a Watermark. Of course removing is, you'd reverse the logic.
How to Watermark Word Documents with PowerShell
#Relevant files
$File = $args[0]
$WM = $args[1]

#Open document in Word
$Word = New-Object -ComObject Word.Application
$Word.Visible = $False
$Doc  = $Word.Documents.Open($File)

#Insert Watermark
Function Watermark
{
    #Create rectangle
    $Shape = $args[0].Shapes.AddShape(1,0, 0, 500, 125)

    #Fill rectanlge with watermark image
    $PicFill = $Shape.Fill.UserPicture($args[1])

    #Hide rectangle lines
    $Shape.Line.Visible = $False

    #Set transparency of watermark
    $Shape.Fill.Transparency = .8

    #Center watermark on width of page
    $Shape.Left = -999995

    #Center watermark on height of page (This was guess and checked)
    $Shape.Top = 250

    #Rotate watermark
    #Rotation rarely works when Word is not visible.  Command left here for reference.
    $Shape.Rotation = 315
}

#Only on 1st Page
#Watermark $Doc $WM

#On all Pages
#Determine number of pages in document
$Bind = 'System.Reflection.BindingFlags' -as [type]
$Doc.Repaginate()
$Prop = $Doc.BuiltInDocumentProperties(14)
$Pages = [System.__ComObject].invokemember('Value', $Bind::GetProperty, $null, $Prop, $null)

#Start at 0 to include any cover pages
For ($i = 0; $i -le $Pages - 1; $i ++)
{
    #Change pages
    $Word.Selection.GoTo(1,2,$null,$i)

    #Apply watermark
    Watermark $Doc $WM
}

#Check version of Word installed and save changes
$Version = $Word.Version
If ($Version -eq '16.0' -Or $Version -eq '15.0') {
    $Doc.Close($True)
}
ElseIf ($Version -eq '14.0') {
    $Doc.Close([ref]$True)
}

#Exit Word
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
$Word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word)

#Cleanup
Remove-Variable Word

You could also, just ---

*

*Opened any Word doc with a watermark.

*Fire up the Word Macro recorder.

*Do what you wish in Word.

*Stop the recorder when done.

*Export the macro code.

*Convert the macro VBA code for use with PowerShell.

A: Here's my solution, cobbled together from "Hey, Scripting Guy!" entries and this question about PowerShell and Word footers.
Function OpenWordDoc($Filename)
{
$Word = NEW-Object –ComObject Word.Application
Return $Word.documents.open($Filename)
}

$Doc = OpenWordDoc -Filename "C:\Users\mynamehere\Downloads\andSuch\WaterMarkDoc.docx"
$Savename = "C:\Users\mynamehere\Downloads\andSuch\SansWaterMarkDoc.docx"

[void]$Doc.Sections.Item(1).Headers.Item(1).range.Delete(1)

Function SaveAsWordDoc($Document,$FileName)
{
$Doc.Saveas([REF]$Filename)
$Doc.Close()
}
SaveAsWordDoc –document $Doc –Filename $Savename


text:
Q: DataFrame object is not callable in sql i'm trying to normalize my data in sql
import pandas as pd
df = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-
databases/glass/glass.data',
header=None)
print(data.shape)

class Normalizer():
   [...]

  X, _ = df(return_X_y=True)
  for norm in ['l1', 'l2', 'max']:
      sc1 = Normalizer(norm=norm).fit(X)
      sc2 = skNormalizer(norm=norm).fit(X)
      Xt1 = sc1.transform(X)
      Xt2 = sc2.transform(X)
      print(np.allclose(Xt1, Xt2))'

but I'm getting this error
TypeError          Traceback (most recent call last)
       in ()
  ----> 1 X, _ = df(return_X_y=True)
      2 for norm in ['l1', 'l2', 'max']:
      3     sc1 = Normalizer(norm=norm).fit(X)
      4     sc2 = skNormalizer(norm=norm).fit(X)
      5     Xt1 = sc1.transform(X)

  TypeError: 'DataFrame' object is not callable

A: You can find the answer in this post here
You either need a DataFrame.var or numpy.var and the link has some samples that will help you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OPA server with input.method policy fails to allow simple correct request I try to get an allow:true for POST request to an opa server, but I get always false no matter what method I use.
This is the policy
package learn.test

import future.keywords.if

default allow := false

allow if {
  input.method == "POST"
}

However, I get an allow true when I put something like
allow if {
  1==1
}

and always false for 1==2, as expected.
I am using insomnia to make the requests. What am I missing?

A: It must be a problem with the input for format.
In most of the cases HTTP method is mostly an internal element not reachable with just input.method. I would try to print the input value and inspect the real value coming as the input.


text:
Q: Passing a numpy function in python to C++ using SWIG directors My code is mainly in C++, but I want to use the SWIG director option to redefine a C++ virtual function in python, and then pass that function back to C++. The following is a simplified example.
Here is my base class in C++ with a virtual function fun. fun takes in (double* x, int n) which allows me to pass a numpy array into it.
class base{
public:
    virtual double fun(double* x, int n){return 0.0;}
};

I have another class which takes in this base class:
class main{
public:
    base* b_;

    main(base& b){
        b_ = &b;
    }
};

This class has a constructor which takes in a base class and stores a pointer to it (b_).
I can successfully compile the swig interface into a module named mymodule making sure to enable directors (see SWIG interface file below), and, as per the SWIG director documentation, I inherit the base class and redefine the virtual function fun as follows:
import mymodule
class base(mymodule.base):
    def __init__(self):
        super(base,self).__init__()
    def fun(self,x):
        return x[0]

Then I pass it into the main class:
b = base()
m = mymodule.main(b)

However, when I try m.b_.fun(array([1.,2.])) I get a TypeError:
TypeError: 'SwigPyObject' object has no attribute '__getitem__'

Any ideas on how to get this to work? I think when I pass b into mymodule.main, C++ is seeing x as a double * pointer and doesn't know what to do with it.
By the way, here is my swig interface file:
%module(directors="1") mymodule

%{
#define SWIG_FILE_WITH_INIT
/* Includes the header in the wrapper code */
#include "myclasses.h"
%}

%feature("director") base;

%init %{
import_array();
%}

%apply (double* IN_ARRAY1, int DIM1) {(double* x, int n)};

/* Parse the header file to generate wrappers */
%include "myclasses.h"

A: It looks like an ownership issue from Python.
Provide a hint to SWIG:
%new double *fun(double* IN_ARRAY1, int DIM1) {(double* x, int n)};

Notice the pointer to the function itself as well.
The Python module will assign proper ownership of the object(s) when %new is used. That's why you can use values but not variables in the call.

A: It seems that director isn't recognizing your Python implementation of fun(double* x, int n); it's not doing the overloading of that function.
I suspect that the reason is due to of the fact that your Python implementation uses numpy as argument. Please note that the director will call either the abstract function or the implemented one.
On the other hand, %apply (double* IN_ARRAY1, int DIM1) {(double* x, int n)} only declares the typemap logic for wrapping the function in Python, not to the director. Note that this is the reason why b.fun(array([1.,2.]) works! Said that, you should declare the typemap logic to the director.
Here you can find how to do it:
%typemap(directorin,numinputs=1) (double *x, int n)
{
    npy_intp dim = $2;
    $input = PyArray_SimpleNewFromData(1, &dim, NPY_DOUBLE, (void *)$1);
}

Hope that this solves your problem and other futures ones :). I got a similar issue and spent few days trying to figure out.


text:
Q: Express eigenvectors of $A^{-1}$ in terms of eigenvectors of $A$ I know the eigenvalues of the matrix $A^{-1}$ are $\frac{1}{\lambda_n}$ where $\lambda_n$ are the eigenvalues of $A$. I didn't know their eigenvectors were related; in what way are they related?
Also how would you prove that $(BC)^{-1} = C^{-1}B^{-1}$? Because I have no idea where to start on that.

A: Hint If $A$ is invertible and ${\bf w} = A {\bf v}$, then ${\bf v} = A^{-1} {\bf w}$. How does this specialize if $\bf v$ is an eigenvector of $A$?

A: Here's a hint for the second question. By the definition of inverses, we have the following:
$$BC \cdot (BC)^{-1}=I$$
In order to get from $BC$ to $I$, you want to cancel out the $C$ on the right and then cancel out the $B$. How would this be written in terms of $B^{-1}$ and $C^{-1}$?

A: $(AB)^{-1} = B^{-1} A^{-1}\\
A = PDP^{-1}\\
A^{-1} = PD^{-1}P^{-1}$


text:
Q: How to split string at specific character and build different string combinations I have some strings in a text file that I want to process. I tried many regex patterns but none of them are working for me.
someone can tell/figure
a/the squeaky wheel gets the grease/oil
accounts for (someone or something)
that's/there's (something/someone) for you

I need the following string combinations:
someone can tell
someone can figure
a squeaky wheel gets the grease
a squeaky wheel gets the oil
the squeaky wheel gets the grease
the squeaky wheel gets the oil
accounts for someone
accounts for something
that's something for you
that's someone for you
there's something for you
there's someone for you

A: edit: corrected for brackets and " or " which I missed last version
A simple recurrent solution that also works with more than one slash (he/she/it/whatever):
def explode_versions(s):
    match = re.search('^(.*?)(\S+)(?:(?:(?: or )|/)(\S+))+(.*?)$', s)

    if match:
        head, *versions, tail = match.groups()

        versions[0] = re.sub('^\(', '', versions[0])
        versions[-1] = re.sub('\)$', '', versions[-1])

        return [line for v in versions for line in explode_versions(''.join([head, v, tail]))]
    else:
        return [s]

texts = ["someone can tell/figure",
"a/the squeaky wheel gets the grease/oil",
"accounts for (someone or something)",
"that's/there's (something/someone) for you"]

[explode_versions(text) for text in texts]

result:
[['someone can tell', 'someone can figure'],
 ['a squeaky wheel gets the grease',
  'a squeaky wheel gets the oil',
  'the squeaky wheel gets the grease',
  'the squeaky wheel gets the oil'],
 ['accounts for someone', 'accounts for something'],
 ["that's something for you",
  "that's someone for you",
  "there's something for you",
  "there's someone for you"]]

A: You can use cartesian product:
from itertools import product
import re

s = 'a/the squeaky wheel gets the grease/oil'

lst = [i.split('/') for i in re.split(r'(\w+[\/\w+]+)', s) if i]
# [['a', 'the'], [' squeaky wheel gets the '], ['grease', 'oil']]

[''.join(i) for i in product(*lst)]

Output:
['a squeaky wheel gets the grease',
 'a squeaky wheel gets the oil',
 'the squeaky wheel gets the grease',
 'the squeaky wheel gets the oil']

A: it's a bit tricky one, but the main idea is to duplicate the options so far when reaching \ and keep track over 2 of the options, take a look on this:
m_str = ['someone can tell/figure',
'a/the squeaky wheel gets the grease/oil',
'accounts for (someone or something)',
'that\'s/there\'s (something/someone) for you']

lines = [[]]
for line in m_str:
    options = [[]]
    for word in line.split(" "):
        if "/" in word:
            new_options = []
            for option in options:
                new_options.append(option + [word.split("/")[0]])
                new_options.append(option + [word.split("/")[1]])
            options = new_options
            # print(new_options)
                # options = [m_func(options, item) for item in options]

        else:
            for option in options:
                option.append(word)
    lines.append(options)
print(lines[1:])

output:
[[['someone', 'can', 'tell'], ['someone', 'can', 'figure']], [['a', 'squeaky', 'wheel', 'gets', 'the', 'grease'], ['a', 'squeaky', 'wheel', 'gets', 'the', 'oil'], ['the', 'squeaky', 'wheel', 'gets', 'the', 'grease'], ['the', 'squeaky', 'wheel', 'gets', 'the', 'oil']], [['accounts', 'for', '(someone', 'or', 'something)']], [["that's", '(something', 'for', 'you'], ["that's", 'someone)', 'for', 'you'], ["there's", '(something', 'for', 'you'], ["there's", 'someone)', 'for', 'you']]]

A: This solves the question for / and or. I did not consider the brackets, but this should be fairly easy to do so :)
lines = ["someone can tell/figure",
         "a/the squeaky wheel gets the grease/oil",
         "accounts for (someone or something)",
         "that's/there's (something/someone) for you"]

result = []
for line in lines:
    sequences = []
    skip = False
    if "/" in line or "or" in line:
        words = line.split(" ")
        temp_words = []
        for index, word in enumerate(words):
            if skip:
                skip = False
                continue
            else:
                if "/" in word:
                    options = word.split("/")
                    if len(sequences) > 0:
                        temp = []
                        for seq in sequences:
                            for opt in options:
                                temp.append(f"{seq} {opt}")
                        sequences = temp
                    else:
                        sequences = options
                elif word == "or":
                    options = [words[index-1], words[index+1]]
                    if len(sequences) > 0:
                        temp = []
                        for seq in sequences:
                            for opt in options:
                                temp.append(f"{' '.join(seq.split(' ')[:-1])} {opt}")
                        sequences = temp
                        skip = True
                    else:
                        sequences = options
                else:
                    temp = []
                    if len(sequences) > 0:
                        for seq in sequences:
                            temp.append(f"{seq} {word}")
                        sequences = temp
                    else:
                        sequences.append(word)

    else:
        sequences = line

    print(sequences)

Output:
['someone can tell', 'someone can figure']
['a squeaky wheel gets the grease', 'a squeaky wheel gets the oil', 'the squeaky wheel gets the grease', 'the squeaky wheel gets the oil']
['accounts for (someone', 'accounts for something)']
["that's (something for you", "that's someone) for you", "there's (something for you", "there's someone) for you"]

A: I wrote a script for you. But I can see, I was not the first one.
I solved your problem by doing a recursive loop. I just pick a bracked and seperate these or a '/'. I can see, compared to the others it's more complex, but it can handle brackets as well (what only marcin archived before) and i think you can quickly adapt it.
Edit: I canged the main, so that one can run ist to open a textfile.
python3 bobafitsscript.py textfile
#!/usr/bin/env python3
def  sep_by_slash(word):
    pos=word.index('/')
    variation1=' '.join(wordlist[:i]+[]+wordlist[i+1:])
    variation2=' '.join(wordlist[:i]+[]+wordlist[i+1:])
    return (word[:pos],word[pos+1:])

def sep(s):
    if '(' in s:
        #veryfi if bracets are vorrect located.
        try:
            pos_start=s.index('(')
            pos_end=s.index(')')
            assert pos_start<pos_end
        except:
            print("ERROR: Mustake with brakets.")
            return None
        else:
            str_start=s[:pos_start]
            str_middle=s[pos_start+1:pos_end]
            str_end=s[pos_end+1:]
            if '/' in str_middle:
                variants=[
                    str_start+possible_word+str_end
                    for possible_word in str_middle.split('/')
                    ]
                return [finite for variant in variants for finite in sep(variant)]
            elif ' or ' in str_middle:
                variants=[
                    str_start+possible_word+str_end
                    for possible_word in str_middle.split(' or ')
                    ]
                return [finite for variant in variants for finite in sep(variant)]
            return [str_start+str_middle+str_end]
    if '/' in s:
        wordlist=s.split()
        for i,word in enumerate(wordlist):
            if '/' in word:
                variants=[
                    ' '.join(wordlist[:i]+[possible_word]+wordlist[i+1:])
                    for possible_word in word.split('/')
                    ]
                return [finite for variant in variants for finite in sep(variant)]
    return [s]

def main(args):
    with open(args[1], 'r') as textfile:
        for line in textfile.readlines():
            for var in sep(line.strip()):
                print(var)
    # ~ for line in sep(args[1]):
        # ~ print(line)
    return 0

def main_directly(args):
    for line in sep(args[1]):
        print(line)
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

Output:
someone can tell
someone can figure
a squeaky wheel gets the grease
a squeaky wheel gets the oil
the squeaky wheel gets the grease
the squeaky wheel gets the oil
accounts for someone
accounts for something
that's something for you
there's something for you
that's someone for you
there's someone for you


text:
Q: AngularJS directive with ng-show not toggling with change in variable I'm trying to create a simple html5 video playlist app. I've got an overlay div on top of the html5 video that should appear/disappear when stopping and starting the video.
I've got ng-show and a variable to trigger it, but it's not changing when I look using ng-inspector.
My events might not be quite correct, either - but I can't seem to find much information on putting events on different elements within the same directive. Is this a clue that I should break this up into multiple directives?
    (function() {
    'use strict';

    angular
    .module('app')
    .controller('campaignController', campaignController)
    .directive('myVideo', myvideo);

    function campaignController($log,Campaign) {
        var vm = this;
        vm.overlay = true;

        Campaign.getCampaign().success(function(data) {
            vm.campaign = data[0];
            vm.item = vm.campaign.videos[0];
        });

        vm.select = function(item) {
            vm.item = item;

        };

        vm.isActive = function(item) {
            return vm.item === item;
        };
    };

    function myvideo() {
        return {
            restrict: 'E',

            template: ['
',
            '
{{ vm.campaign.name}}
',
            '',
            '
',
            '<video class="video1" controls ng-src="{{ vm.item.video_mp4_url | trusted }}" type="video/mp4"></source>',
            '</video>' ].join(''),
            link: function(scope, element, attrs) {
                scope.video = angular.element(document.getElementsByClassName("video1")[0]);
                scope.startbutton = angular.element(document.getElementsByClassName("start")[0]);

                scope.startbutton.on('click', function() {
                    scope.vm.overlay = false;
                    scope.video[0].play();

                });
                scope.video.on('click', function() {
                    scope.video[0].pause();
                    scope.vm.overlay = true;
                });

            }
        };
    }
})();

A: From my personal experience angular expression evaluation does not work as javascript. so try ng-show="vm.overlay==true".
Furthermore you bind click using native javascript.
Either don't do that and use ng-click or call scope.$apply() in the click event t callbackas last intruction (even though i'm not sure if it's really important).


text:
Q: Is it possible to hide a library dependency if it's a template class? I have a library A that uses library B. I want the user of A to use a templated class from B library. But A and B have different namespaces, is it possible to encapsulate/hide that class from B in A namespace?
I tried to use PIMPL but ... It's a template, so don't know exactly how can I do it.
For reference the class that I want to encapsulate in my library is:
namespace anax {
template <typename T>
class Component : public BaseComponent
{
public:

    static detail::TypeId GetTypeId()
    {
        return detail::ClassTypeId<BaseComponent>::GetTypeId<T>();
    }
};

}

So the users of A, have to do for example:
   class Position: public anax::Component<Position>
   {
       float x,y,z;
   }

What I'm asking exactly is if it's possible to encapsulate/hide this anax::Component class inside my namespace like this:
   class Position: public myAnamespace::Component<Position>
   {
       float x,y,z;
   }

A: How about:
namespace myAnamespace{

    template<class Position>
    using Component = anax::Component<Position>;
}

Or, in pre-C++11,
namespace myAnamespace{

    template<class Position>
    struct Component
    {
         typedef anax::Component<Position> type;
    };
}

A: namespace anax
{
  class Component
  {
  };
};

namespace b
{
  using namespace anax;
  class Position : public Component
  {
  };
};


text:
Q: Summing Numbers in an Array Greater than an Inputted Value Need to add all numbers in an array that is greater than an inputted number. The seed is just so the output can be replicated.
Example:
[12,16,45,3,32]
Inputted Value: 30
Output:
77
import java.util.*;

    public class SumAbove {
        public static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
            int seed = scnr.nextInt();
            Random rand = new Random(seed);

            System.out.println("Enter a positive integer between 1-100 to search above:");
            int minVal = scnr.nextInt();

            int[] arr = new int[rand.nextInt(100)+1];
            for (int i=0; i<arr.length; i++) {
                arr[i] = rand.nextInt(100)+1;
            }
            System.out.println(Arrays.toString(arr));

             int sum = 0;
             for (int i=0; i<arr.length; i++) {
             if (arr[i]>minVal) {
                    sum += i;
                }
             }
            System.out.println(sum);
        }
    }

A: Instead of sum += i; you want sum += arr[i]; (as already noted), you also only need one loop (since you know the minimum before the first loop). Like,
int minVal = scnr.nextInt(), sum = 0;
int[] arr = new int[rand.nextInt(100) + 1];
for (int i = 0; i < arr.length; i++) {
    arr[i] = rand.nextInt(100) + 1;
    if (arr[i] > minVal) {
        sum += arr[i];
    }
}
System.out.println(Arrays.toString(arr));
System.out.println(sum);

A: Replace sum += i with sum += arr[i].
The variable i is just the position. arr[i] is the value at that position.

A: public static void main(String[] args) {

    int nums[] = { 12, 16, 45, 3, 32 };
    int value;
    int sum = 0;

    System.out.println("Enter a positive integer between 1-100 to search above: ");
    Scanner sc = new Scanner(System.in);
    value = sc.nextInt();

    for (int i = 0; i < nums.length; i++) {
        if (nums[i] > value)
            sum = nums[i] + sum;
    }
    System.out.println(sum);
}

A: Here is how you can do it with streams in Java 8+.
      int nValues = 5;
      int minValue = 1;
      int maxValue = 30;
      Random r = new Random();
      for (int i = 0; i < 10; i++) {
         int[] values = r.ints(nValues, minValue, maxValue + 1).toArray();

         // min to sum is the threshold
         int minToSum = r.nextInt(7) + 10; // between 10 an 16 inclusive

         int sum = Arrays.stream(values).filter(m -> m > minToSum).sum();

         System.out.println("sum = " + sum + " for greater than " + minToSum
               + " : " + Arrays.toString(values));
      }

The following output.
sum = 65 for values greater than 11 : [2, 10, 14, 23, 28]
sum = 92 for values greater than 10 : [13, 18, 15, 19, 27]
sum = 94 for values greater than 12 : [25, 6, 14, 25, 30]
sum = 54 for values greater than 10 : [14, 8, 14, 26, 5]
sum = 22 for values greater than 15 : [15, 8, 13, 22, 14]
sum = 28 for values greater than 13 : [3, 28, 9, 6, 5]
sum = 87 for values greater than 13 : [5, 18, 25, 21, 23]
sum = 31 for values greater than 13 : [16, 7, 12, 2, 15]
sum = 42 for values greater than 15 : [7, 22, 20, 10, 5]
sum = 40 for values greater than 12 : [2, 2, 13, 27, 9]


text:
Q: How to use SQL Data Adapter Update command to update a row in data table So far I managed to use Insert command to create a new record inside a table called "Students". This is the code i used:
        int ID = int.Parse( TextBox1.Text);
        string name = TextBox2.Text;
        string gender = TextBox3.Text;
        int marks = int.Parse(TextBox4.Text);

        string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

        using (SqlConnection con = new SqlConnection(CS))
        {
            //create data adapter
            SqlDataAdapter adapter = new SqlDataAdapter("select * from students",con);

            //create sqlcommand to store execute stored procedure
            adapter.InsertCommand = new SqlCommand("spInsertStudent",con);
            adapter.InsertCommand.CommandType = CommandType.StoredProcedure;

            //create parameter for Return value (@ROWCOUNT)
            SqlParameter parameter = adapter.InsertCommand.Parameters.Add("@ROWCOUNT",SqlDbType.Int);
            parameter.Direction = ParameterDirection.ReturnValue;

            adapter.InsertCommand.Parameters.Add("@ID", SqlDbType.Int, 0, "ID");
            adapter.InsertCommand.Parameters.Add("@Name",SqlDbType.NVarChar,50,"Name");
            adapter.InsertCommand.Parameters.Add("@Gender",SqlDbType.NVarChar,10,"Gender");
            adapter.InsertCommand.Parameters.Add("@TotalMarks",SqlDbType.Int,0,"TotalMarks");

            DataSet ds = new DataSet();
            //DataTable students = new DataTable();
            adapter.Fill(ds,"Students");

            DataTable students = ds.Tables["Students"];

            DataRow studentRow = students.NewRow();
            studentRow["ID"] = ID;
            studentRow["Name"] = name;
            studentRow["Gender"] = gender;
            studentRow["TotalMarks"] = marks;
            students.Rows.Add(studentRow);

            adapter.Update(ds,"Students");

Now I want to edit a data row. The data will be change if the ID is matched with the ID parameter. This is the stored procedure I'm using:
create procedure updateStudent
@ID int,
@Name varchar(50),
@Gender varchar(10),
@TotalMarks int

AS
BEGIN
    update Students set Name = @Name, Gender = @Gender, TotalMarks = @TotalMarks
    where ID = @ID
END

and this is the C# code i use in the code behind:
        int ID = int.Parse(TextBox1.Text);
        string name = TextBox2.Text;
        string gender = TextBox3.Text;
        int marks = int.Parse(TextBox4.Text);

        string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            SqlDataAdapter adapter = new SqlDataAdapter("Select * from Students",con);
            DataTable dtStudents = new DataTable();
            adapter.Fill(dtStudents);
            SqlCommand cmd = new SqlCommand("updateStudent",con);
            cmd.Parameters.Add("@ID", SqlDbType.Int, 0, "ID").Value = ID;
            cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name").Value = name;
            cmd.Parameters.Add("@Gender", SqlDbType.NVarChar, 10, "Gender").Value = gender;
            cmd.Parameters.Add("@TotalMarks", SqlDbType.Int, 0, "TotalMarks").Value = marks;
            adapter.UpdateCommand = cmd;

            adapter.Update(dtStudents);
        }

But after I clicked the Update button on my web form, there is no error message and the data didn't get updated in my database. What have I did wrong here?

A: I think you should write classes for executing stored procedures. It will be more easier to read and handle. RunQuery method in such a class like DB
 private SqlConnection Connection;
 public bool Open()
 {
    try
    {
       ConnectionString = "your connection string";
       Connection = new SqlConnection(ConnectionString);
       Connection.Open();
       return true;
     }
     catch (Exception ex)
     {
        errorMessage = ex.Message;
        return false;
     }
 }
 public bool RunQuery(string ProcedureName, SqlParameter[] Parameters)
 {
     bool res = false;
     try
     {
         SqlCommand Command = new SqlCommand();
         Command.CommandText = ProcedureName;
         Command.CommandType = CommandType.StoredProcedure;
         Command.Connection = Connection;
         Command.Parameters.AddRange(Parameters);
         Command.ExecuteNonQuery();
         res = true;
      }
      catch (Exception ex)
      {
         throw ex;
      }
      return res;
  }

And you can call it
SqlParameter[] param= new SqlParameter[4];
param[0] = new SqlParameter("@ID", ID);
param[1] = new SqlParameter("@Name", name);
param[2] = new SqlParameter("@Gender", gender);
param[3] = new SqlParameter("@TotalMarks", marks);
RunQuery("updateStudent", param);


text:
Q: Needed power to make an antenna work A dipole antenna with a frequency of 90Mhz has a wavelength of approximately 3.33103 meters and an antenna length of (=wavelength/2) 1.66 meters. The minimum voltage to make the antenna work will be depending on the efficiency of material and distance. Is it possible to make the antenna length shorter than what it should require as mentioned above with a smaller voltage to make use of transmitter antenna for 90Mhz radio communication?

A: In short: There's no "minimum power". An antenna is a linear thing. It "works" with as arbitrarily little energy you put in (unless you're a quantum physicist, which I don't think you are).
Of course, the less power you put in, the less it puts out – proportionally. That's the thing with linearity.
Also, no, you cannot just change your antenna dimensions; that changes the frequencies at which the antenna is efficient at. (and has nothing to do with power.) You even say that you want a half-wavelength antenna, so what makes you think you can change the antenna length while keeping the wavelength?
It seems you should refresh a bit of antenna basics.


text:
Q: Can you transfer iPhone backups made on Windows to a Mac? I made an iPhone backup on someone else windows computer and now need to send it to my Mac to restore my iPhone because it got bricked. If I simply send the file over a torrent and put it in the backup folder on my Mac's iTunes, will I have any trouble with restoring my device? I'm worried the format that iTunes on windows uses is different then on Macs'.
follow up question: Is there a better way then a torrent to send a file about 50gb?

A: The backup format is the same for Mac and Windows, so you can copy your backup from the C:\Users\[USERNAME]\AppData\Roaming\Apple Computer\MobileSync\Backup folder on your Windows computer to ~/Library/Application Support/MobileSync/Backup on your Mac yes. If you need instructions for various versions of Mac and Windows to access these folders, here's a blog post I wrote with them.
If you have a USB thumb drive, that may be better to copy the 50GB backup. :) You could also right-click on the folder for the backup and select Send To > Compressed Folder first to zip it.

A: BitTorrent is actually quite well suited to transferring very large files or groups of files. It can be a good choice, especially if the user is already familiar with it.
The BitTorrent protocol:

*

*is (relatively?) efficient

*tolerates errors well and can recover from interrupted transfers

*doesn't have some of the inefficiencies / overhead of the SMB3 protocol used by modern file sharing on macOS and Windows, especially if you're transferring a folder containing many (i.e. hundreds or thousands) of separate files.

Notes:

*

*Just transfer over the actual '.torrent' file,
a. or use a magnet link in clients with 'local peer discovery enabled.

*For private files, just don't publish the '.torrent' file to any trackers.

If you aren't familiar with BitTorrent, Resilio Sync uses the same technology but without the 'scary' BitTorrent name. It works much like Dropbox _(but without any data stored in 'the cloud') and is just as easy to set up. Free for home use.
If you were to make the iOS backup directly into a folder shared by Resilio Sync on both computers, you might actually find that most of the data is already synchronized before the backup is even complete!

Regardless of the program one uses, depending on network speed, a local network transfer is very likely to be faster than even a good quality USB 3 'thumb drive'.


text:
Q: Вывод по ключу в порядке убывания. Есть простая хеш-функция key%m;
Массив из m=20 элементов
Есть 100 объектов, с рандомными ключами.
Массив представляет собой массив стеков.
Задача:
Вывести элементы в порядке убывания ключа.
Проблема собственно в том, что самый максимальный ключ находится к примеру в 20 ячейке, следующий максимальный в 1, затем во второй, затем опять в 20-й.
Т.е. приходится вот так вот прыгать.
Собственно какие у меня варианты?
Собирать всё это в отдельный массив, сортировать его и потом выводить наверное не вариант.


text:
Q: Activate profile when a certain Maven goal is run I'm looking for a generic solution to enable a Maven profile when a certain Maven goal is run. For example, if I run
mvn site

I also want to activate the profile reporting automatically. I don't want to do it manually, e.g., using:
mvn site -Preporting

I expected that in the activation part of a profile I can specify a Maven goal, triggering the profile to get enabled, but this doesn't seem the case.
Another idea was that I could somehow configure a property to get set if a certain goal is run, because a profile can be activated by a property. But I haven't really found a way how to do that.
Is there a generic solution?

A: I doubt this is a good idea, really.
Maven adheres to the concept of repeatable builds. If running "mvn site" somehow changes the local build configuration so that this (or the next Maven command) runs with a profile enabled means subsequent builds might behave differently.
Instead, you may be able to attach the reporting requirements to the mvn site goal (or another goal).
Therefore, mvn site will also run reporting.


text:
Q: Guidelines for good webcrawler 'Etiquette' I'm building a search engine (for fun) and it has just struck me that potentially my little project might wreak havok by clicking on ads and all sorts of problems.
So what are the guidelines for good webcrawler 'Etiquette'?
Things that spring to mind:

*

*Observe Robot.txt instructions

*Limit the number of simultaneous requests to the same domain

*Don't follow ad links?

Stopping the crawler from clicking on ads
 - This one is particularly on my mind at the moment... how do i stop my bot from 'clicking' on ads? if it is going straight to the url in the ad is it counted as a click?

A: You don't read only the robots.txt instruction. You should also see the meta tags with noindex and nofollow.
About the ad question, I'm not sure, but I guess if you just read the links and then some other time enter the page, the entered page will have no info on how you got that address, and can't charge the site for the "pseudoclick"

A: Don't follow links marked as rel="nofollow".
Also, you don't have to worry about ads. If you spider only HTML text of a page, then in most cases you won't get ad links there - they are generated on client using javascript.


text:
Q: How to create an element with information put in the form after being submitted? I want to create this small app that would be something like a typical contact list with phone numbers and names of people. Essentially, I want all the information I put in the form (First Name, Phone Number etc) to be displayed below the List of Phone Numbers, but I'm having issues writing a working function in JavaScript.
const form = document.querySelector('#phone-form');
const list = document.querySelector('.phone-list');
const inputPhone = document.querySelector('#addPhone');
const inputFirstName = document.querySelector('#addPhone');
const inputLastName = document.querySelector('#addPhone');

function loadEventListener(){
form.addEventListener('submit', addPhone);
}

function addPhone(e){
if(inputPhone.value === ' ' &&
   inputFirstName === ' ' &&
   inputLastname === ' ') {
       alert('Missing information');
   }

const li = document.createElement('li');
li.appendChild(document.createTextNode(inputPhone.value));
li.appendChild(document.createTextNode(inputFirstName.value));
li.appendChild(document.createTextNode(inputLastName.value));

list.appendChild(li);

e.preventDefault();
}

And here's the HTML:
 <form id="phone-form">
 Phone Number
 <input placeholder="Enter phone number" id="phone-number"></input>
 First Name
 <input placeholder="First Name" id="first-name"></input>
 Last Name
 <input placeholder="Enter last name" id="last-name"></input>
 <button type="submit" id="addPhone">Add Phone</button>

List of Phone Numbers

A: In your querySelectors at the top, you have the incorrect ids being selected. They do not match up with your HTML ids.

A:

const form = document.querySelector('#phone-form');
const list = document.querySelector('.phone-list');
const inputPhone = document.querySelector('#phone-number');
const inputFirstName = document.querySelector('#first-name');
const inputLastName = document.querySelector('#last-name');
console.log(inputPhone);

form.addEventListener('submit', addPhone, false);

function addPhone(e){
e.preventDefault();

if(inputPhone.value === ' ' &&
   inputFirstName === ' ' &&
   inputLastname === ' ') {
       alert('Missing information');
   }

let li = document.createElement('li');
li.appendChild(document.createTextNode(inputPhone.value));
li.appendChild(document.createTextNode(inputFirstName.value));
li.appendChild(document.createTextNode(inputLastName.value));

list.appendChild(li);
}
<form id="phone-form">
 Phone Number
 <input placeholder="Enter phone number" id="phone-number"></input>
 First Name
 <input placeholder="First Name" id="first-name"></input>
 Last Name
 <input placeholder="Enter last name" id="last-name"></input>
 <button type="submit" id="addPhone">Add Phone</button>
 </form>

first


text:
Q: Customize BrowseFragment So I want to customize rows in order to get this.

I want to see the details above focused item but I'm not sure which approach I need to take.Can anyone help me this one ?

A: As I can't comment, I'll have to put an answer.
I don't know if I understand your question entirely, but you want when focused on an item like video 1 or video 2, to show some details.
First approach is to make text views in the places where you want to show the data and initially set their visibility to GONE, and the on click on the item set them to VISIBLE.
The other approach I can think about is using alert dialog, as on click to open a popup window with the details.
The first approach is more to your liking and description in the question but I liked to give you some other choice too.
If I haven't totally understood the question, tell me more and I will edit my answer regarding the details.


text:
Q: Largest sum of subset of a matrix with condition I have a problem: Given a matrix A, find the (sub)set C with largest sum, which consists of a_{ij} elements of matrix A, such that no two members of C share the same column or same row in A.
So far I have not found the optimum solution to it, and I do not know what classifications it belongs. So please help!
Thanks a lot!


text:
Q: La comparación de dos String siempre me da false aunque sean iguales Tengo un método para verificar el contenido de un JSONArray, su función es verificar cuantas veces aparece cierto valor en una clave específica del array y contabilizar cuantos valores diferentes hay para todo el array.
El JSONArray tiene el siguiente formato:
{"array":[
  {"package":"com.example.1","resource":"permissions"},
  {"package":"com.example.1","resource":"image"},
  {"package":"com.anotherexample.2","resource":"permissions",
  {"package":"com.anotherexample.2","resource":"image"}
]}

Entonces utilizo Gson para parsear este JSONArray a una clase personalizada preparada para recibir estos datos. Me saltaré el código de la clase para evitar llenar la pregunta de código.
Ya verifiqué y se parsea correctamente, todo el arreglo se guarda correctamente en un objeto de tipo List así que el error no está acá...
Ahora, quiero determinar por ejemplo, cuantas veces aparece el package con el valor com.example.1 para determinar cuantos paquetes diferentes contiene el array. Para esto tengo el método siguiente:
public int getPackagesCount(List<MiClaseParaParsear> array) {
  int result = 0;
  String control = "";
  int count = array.size();
  for(int x =0; x < count; x++) {
      if(array.get(x).getPackage() == control) {
      // aquí no hago nada porque en teoría el paquete ya fue contabilizado
      } else {
      // aquí aumento en 1 el conteo de package con valores diferentes
          result++;
      // luego asigno a la variable control el valor del package actual para que sirva en el comparador del if, al menos en teoría
          control = array.get(x).getPackage();
      }
  }
  return result;
}

En teoría, lo que este método hace, es ir recuperando uno a uno los valores de package para cada objeto MiClaseParaParsear y compararlos con la variable control para verificar si ese valor de package ya fue contabilizado anteriormente, si es así, no realiza ninguna acción y vuelve al inicio del bucle for, pero si no ha sido contado entonces aumenta en 1 el valor de result que es quien lleva el conteo de los nuevos valores encontrados y asigna el contenido de la clave package a la variable control para que de esta forma en el if ahora se compare con este valor y así determinar si ya fué contado o no.
Usando Log() he logrado ver que si almacena de forma correcta el valor extraído del List, aumenta correctamente el valor de result, pero lo que no hace y no entiendo por qué, es comparar de forma correcta el if. Me explico:
Cuando entra al if, aunque el valor de array.get(x).getPackage() sea igual al valor contenido en control, sigue arrojando false y por ende sigue contabilizando el ppackage aunque este ya haya sido contado, entonces, si tengo un array con 20 valores que se reparten entre 4 package diferentes, el método me devuelve 20 que es el número total de items en el array y no 4 que sería la cantidad de package diferentes que existen en el array.
Como podría hacer lo que busco, o por qué es que el if al parecer no compara de forma correcta los valores?, ya verifiqué que las variables coincidan entre si, al hacer array.get(x).getPackage() obtengo un String, y la variable control también es de tipo String...
Gracias de antemano.

A: para comparar cadenas se usa .equals()
en tu caso seria: if(array.get(x).getPackage().equals(control))

A: El problema radica en la comparación que realizas
if(array.get(x).getPackage() == control) {

el método equals() es el indicado para realizar la comparación entre valores tipo String
if(array.get(x).getPackage().equals(control)) {

Puedes revisar esta pregunta: Como comparar correctamente Strings en Java.


text:
Q:   seo link tag i know
Hamburger
 are good, but how about this:

Food » Hamburger

or thats are ok for google seo?

A: The  tag with an anchor link inside it will work same as a normal  tag for Google SEO. Both the methods are Ok, but the problem that can occur is your readers may go away because you added a hyperlink in the Heading text of your webpage. So, it is not a good practice to use hyperlinks in  tags or any  tag.


text:
Q: Oracle SYSTPH* Type We've noticed in the TOAD schema browser some weird types which seem to pop up randomly throughout the day on our database.  We found them by using the Schema Browser in TOAD under Types -> Collection Types.  They have names like these:
SYSTPHYP5bsxIC47gU0Z4MApeAw==
SYSTPHYP8cBHQYUDgU0Z4MApvyA==
SYSTPHYPwYo541RfgU0Z4MAqeTQ==

They seem to have randomly generated names and we're pretty sure our application is not creating them.  They are all TABLE OF NUMBER(20)
Does anyone have an explanation of what these types are for?

A: These are most likely related to use of the collect aggregate function.  You can find some info here on them:
http://orasql.org/2012/04/28/a-funny-fact-about-collect/
Looks like in the past there was a bug (Bug 4033868 fixed in 11g) where these types did not clean up after themselves.


text:
Q: Recursion not working while traversing through the tree I have a tree structure where at every node there is a list of documents (document length can vary from 5 to 500), and each document contains a number of words. I want to store in how many documents each word appears in the form of a dictionary.
For example: If the document at any node A = [['b','m','n'],['b'],['g'],['o','b','g'],['b','g']]
The count should be stored in each node like A.occurlist = {'b':4,'m':1,'n':1,'g':3,'o':1
I am running the below code but it is not able to incur recursion and showing error: TypeError: 'dict' object is not callable
Code:
def occurlist(node):
    wordSet = set()
    lis = []
    next_node = []
    child_nodes = node.children
    for child in child_nodes:
        next_node.append(child)
        lis += child.documents
    wordSet = set(itertools.chain.from_iterable(lis))
    occurDict = {word:0 for word in wordSet}
    for child in child_nodes:
        occurlist = {}
        occurlist.update(copy.deepcopy(occurDict))
        for doc in child.documents:
            for word in wordSet:
                if word in doc:
                    occurlist[word] +=1
        child.occurlist = occurlist
        print child.name
    print len(next_node)
    if next_node:
        for nn in next_node:
            if not nn.update:
                occurlist(nn)

occurlist(Savings_Accounts)

Savings_Accounts is the name of root node.

A: If you only want the count of each element use collections.Counter:
from collections import Counter

A = [['b','m','n'],['b'],['g'],['o','b','g'],['b','g']]

dict(Counter([ele for sub in A for ele in set(sub)]))
#{'b': 4, 'm': 1, 'g': 3, 'o': 1, 'n': 1}


text:
Q: How can i call a function inside a function inside a class? I have a problem here in the code there is a function inside a function inside a class and I can't find a way to run the second function.
class startFunctionButton(npyscreen.ButtonPress):
    def whenPressed(self):
        IPScanForm.returnData ### Here should the function start

class IPScanForm(npyscreen.NPSApp):
        ip=""
        def main(self):
            f = npyscreen.FormWithMenus(name="Main Menu")
            IPselect = f.add(npyscreen.TitleText,name="IP Address: ")
            convertButtn = f.add(startFunctionButton,name="Start Function")

            def returnData(self): ### the second function
                IPScanForm.ip = IPselect.value ### thats just a placeholder could be anything


text:
Q: Install kube-prometehus-stack get stuck on hook complication We are trying to install kube-prometheus-stack and the installation get stuck (few hours) with the following message:
MESSAGE  "waiting for completion of hook policy/PodSecurityPolicy/prometheus-kube-prometheus-admission and 6 more hooks "  ,
is it a known issue?
what could be the reason? is there a way to avoid it?
https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack


text:
Q: using an array from PHP in a JS file I have an array in my index.php which is created by a foreach:
foreach ($events as $eventkey =>$event)
                {
                    echo "
".$event->title."A
".$event->city."
";
                    $LocationArray[]= $event->latlng;
                }

                json_encode($LocationArray);

Now I want to use this array, in my  javascript ( which is written in a different file..). But CAN I do this? and if so, how? (I'm new to php, and I'm really bad at AJAX stuff etc.. I've been looking around here and other sites but I can't really find the solution.)
The plan is to be able to loop over the array in my javascript and place markers at a google map which I have on my site.

A: You are expecting a valid json output right?
    <?php
    foreach ($events as $eventkey =>$event)
    {
    echo "
".$event->title."A
".$event->city."
";// remove this thing or maybe place it in a variable. do not echo it.
    $LocationArray[]= $event->latlng;
    }

    echo json_encode($LocationArray);

on your script
    $.ajax({
        url:"",
        success: function(data){
            var json = jQuery.parseJSON( data );

            for (var i = 0; i < json.length; i++) {
                alert(json[i]);
                //Do something
            }
        }
    })

A: The simplest solution would be to insert a new script tag with a javascript variable, and then assign the php array to that variable with json_encode. JSON (JavaScript Object Notation) is a text format for data-interchange between programming languages. Because JSON is based on the JavaScript decoding is not needed on the client side.
echo '';

A: You would ideally use AJAX and fetch the output of json_encode($LocationArray)...
so your last line needs to be
echo json_encode($LocationArray);

Once this is taken back by the JS function that initiated the AJAX call, you can convert it into an array and loop it around. (expecting you are using jQuery, the code would look something like this...)
$.ajax({
    url: 'index.php',
    success: function(response) {
        var resData = $.parseJSON(response);
        for (var i = 0; i < resData.length; i++)
        {
            alert(resData[i]);
        }
    }
});

A: The easiest way I can think of is to do an echo before you link to the JS file.
echo""

That has not been debugged or tested, but it should give you the idea.


text:
Q: How to split condition columns into factor levels to perform 2x2 ANOVA I have a dataframe as follows:
dat <- structure(list(Age = c(20L, 20L, 20L, 19L, 19L, 20L, 20L, 25L,
19L, 19L), Gender = c(1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L),
    NoAS_Ver = c(2.125, 3.25, 1.875, 2.625, 3, 2.25, 3, 2.75,
    3.625, 1.75), NoAS_VerDemo = c(3, 3, 2.125, 3.5, 2.625, 2.5,
    3.125, 2.625, 3.25, 3.125), AS_Ver = c(2.875, 2.875, 2, 2.875,
    2.38, 2.875, 2, 2.875, 2.375, 1.625), AS_VerDemo = c(2.125,
    3.625, 3.375, 2.125, 3.25, 2.5, 2.5, 2.75, 4, 2.375)), row.names = c(NA,
10L), class = "data.frame")

There is an age column, a gender column and 4 condition columns. I want to be able to perform a 2X2 repeated measures ANOVA but to do this, I need to split my condition columns so i can work with the levels.
I would like to split them into a "task level" (NoAs or AS) column, a "presentation level" (Ver or VerDemo) column and a "values" column whereby every row is an observation.
I feel like this can be done using the tidyr package however I'm unsure. So far I've tried:
split_dat <- dat %>%
  separate(NoAS_Ver, c(sep = "NoAS", "Ver")) %>%
  separate(AS_Ver, c(sep = "AS", "Ver")) %>%
  separate(NoAS_VerDemo, c(sep = "NoAS", "VerDemo")) %>%
  separate(AS_VerDemo, c(sep = "AS", "VerDemo"))

However this isn't what I'm looking for as I generate a lot of NA values. Does anybody have any tips on what else I can try?

A: Think I've solved my problem:
split_data <- dat %>%
      gather("NoAS_Ver", "NoAS_VerDemo", "AS_Ver", "AS_VerDemo", key = "condition", value = "correctpairs") %>%
      separate(condition, into = c("task", "presentation"))

dat <- structure(list(Age = c(20L, 20L, 20L, 19L, 19L, 20L, 20L, 25L,
19L, 19L), Gender = c(1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L),
    CT = c("NoAS", "NoAS", "NoAS", "NoAS", "NoAS", "NoAS", "NoAS",
    "NoAS", "NoAS", "NoAS"), Pres = c("Ver", "Ver", "Ver", "Ver",
    "Ver", "Ver", "Ver", "Ver", "Ver", "Ver"), correctpairs = c(2.125,
    3.25, 1.875, 2.625, 3, 2.25, 3, 2.75, 3.625, 1.75)), row.names = c(NA,
10L), class = "data.frame")


text:
Q: Closing Bootstrap modals in android with phonegap I am using this bootstrap modals (popups) and they work great in my browser. The problem is, when I launch them on android using phonegap, they do not close when the close button is pressed. When I click on the ovelay next to the popup, everything seems to be working alright ;/ I am very confised...
EDIT: I use exactly the same code as in the example and something goes wrong...

A: I added this function to my angular.js controller:
$scope.closeModal = function (idOfModal) {
    $(idOfModal).modal('hide');
}

And also to the confirm/save buttons of modals, after the controller's function is executed, at the very end again I add $(idOfModal).modal('hide');, where I also pass idOfModal to the function ;)


text:
Q: Needs and this.get('controllers') give wrong results when used with outlet in partial view? Hi and thanks a lot for your precious help on this problem.
As I am quite new in EmberJS' world, problem may come from me and not Ember, but I don't find the right way to fix it.
I have a template named a, a view named AAView (with its template, too) and two controllers AAController and BController.
Template 'a' is rendered by using partial method :
{{partial 'a'}}
AAController is controller for AAView, connected to AAOutlet which is in 'a' template with
this.render('aa', {
    outlet: 'AAOutlet',
    into: 'application'
});

In this AAView, I have an observer that should observes isShown property of AAController.
App.AAView = Ember.View.extend({
    visibilityDidChanged: function() {
        console.log('Visibility just changed man! Do something!');
    }.observes('controller.isShown')
});

This isShown variable is in AAController then...
App.AAController = Ember.ObjectController.extend({
    isShown: false
});

And this variable is set in an other controller (BController) :
App.BController = Ember.ObjectController.extend({
    needs: ['AA'],
    myVal: '',
    myValDidChanged:function() {
        //Conditions and a lot of interesting stuffs
        this.get('controllers.AA').set('isShown', true);
    }.observes('myVal')
});

When my script is executed and reach this code, the view is not notified about the change in controller...
If I stop debugger on this.get('controllers.AA').set('isShown', true); line, it seems that this.get('controllers.AA') returns an other (or a new ?) controller and not the controller used and observed by the view.
Thus where is the problem and how can I retrieve the right controller in BController to edit the value and trigger the observer in the view ?
--> Here is a jsFiddle with a simplified version of the problem.
Huge thanks for your help on this one!

A: xpost from https://github.com/emberjs/ember.js/issues/3404
@Gerfaut There are several points of confusion here.
Among them is using "AAController" as a name- this causes some serious mis-direction. When you render into the outlet with:
this.render('aa', ...

AaController will be resolved, not AAController. The same goes for AAView, it was not hooked up to the UI at all. AaView was instead wired in.
Take a look at: http://jsfiddle.net/x6emd/3/ which resolves your issues by using the correct naming scheme.
I recommend using:
window.App = Ember.Application.create({
  LOG_TRANSITIONS: true, // basic logging of successful transitions
  LOG_VIEW_LOOKUPS: true,
  LOG_ACTIVE_GENERATION: true
});

To help you debug naming issues.

A: When controllers are instantiated by Ember they are assigned a name that begins with a lowercase letter. This is consistent with Ember naming conventions. Try this.get('controllers.a').


text:
Q: Angular js: Cannot create property 'type' on string i want disable image with angular js i used a function to do that i have this error  Cannot create property 'type' on string:
Controller :
 $scope.ActivePlaceSpotCAM = function (idPlace, typePlace) {
        var res = null;
        angular.forEach($scope.ListPlaces, function (value, key) {
            angular.forEach(value.type, function (value ,key) {
                if (value.type = typePlace && value.id == idPlace) {
                    res = value;
                }

            });
        });
        return res;
    }

html :

A: You are doing assignment operation in if please correct
 if (value.type = typePlace && value.id == idPlace)

to
if (value.type == typePlace && value.id == idPlace)
And please check the type of value it should not be a string.Before comparing you should check weather the type property is existing or not.


text:
Q: Do all parallelizable manifolds admit a flat metric? A simply connected manifold $M$ admits a flat metric/connection if and only if $M$ is parallelizable.
What happens/can happen if $M$ is notsimply-connected?
Definitions:
https://en.wikipedia.org/wiki/Parallelizable_manifold
https://en.wikipedia.org/wiki/Simply_connected_space

A: Your assertion is not true, the 3-sphere $S^3$ is a Lie group so it is parallelizable but it does not admits a flat metric, since compact manifolds which admit a flat metric are finitely covered by the n-torus $T^n$.

A: Each parallelizable $n$-dimensional manifold $M$ admits a flat affine connection on $TM$ (the trivial connection). This, of course, does not yield a flat metric. However, if you have a connected noncompact parallelizable manifold (no need to assume simply connected), it does admit a (typically incomplete) flat Riemannian metric. This is an application of the Hirsch-Smale immersion theory: Find an immersion $M\to R^n$ and pull-back the flat metric. On another hand, if $M$ is simply connected and $TM$ has a flat affine connection, then $M$ is indeed parallelizable. (If the connection is complete, then even more is true: $M$ is diffeomorphic to $R^n$.)


text:
Q: What's the difference between facebook.stackoverflow.com and stackoverflow.com? What is the difference between facebook.stackoverflow.com and stackoverflow.com aside from the subdomain and the other title?
Both pages are using the same questions and the same user profiles/information.
On facebook.stackoverflow.com I can also see my questions not related to facebook:
http://facebook.stackoverflow.com/questions/12567518/how-to-handle-dynamically-loaded-managed-libraries-in-c-sharp
When I set my favorite tags to some facebook tags and nothing else then is the only difference the title, the icon and the subdomain, or are there notable special features on facebook.stackoverflow.com?

A: The FSO filter only displays questions containing one of the Facebook related tags.


text:
Q: How to sync Flutter DB with Rails/Phoenix Server I was wondering in 2023 how does one sync data from offline to the cloud with flutter, without Firebase?
I have a Phoenix server that I want to sync it to but I'm struggling to find anything solutions besides firebase. And when there isn't firebase I'm hearing packages like moor or flutter_data but when I investigate it, there doesn't seem to be many how to's out there that are up to date on how to do the syncing. Maybe I'm missing something though.
Additionally is there a specific term for what I'm looking for?
I'm contemplating about switching to something else that isn't flutter because offline first is the only reason I'm making this.


text:
Q: The right Way to instantiate xserver-xorg-video-dummy driver at boot time for CRON scheduled WINE app The context: I have a Windows based apps provided by a data service provider. I have managed to get this to work in WINE. The app requires a GUI (initial configuration, login credentials and exception data management) for initial and adhoc tasks. I configured remote RDP into tightvncserver/xfce4. It works well.
I need to schedule data updates (multiple times per day). However the app does require a GUI environment so I setup the headless display manager (xserver-xorg-video-dummy driver). From a terminal I can manually start "X &" and then instantiate the windows app. Loving Ubuntu so far :)
...
DISPLAY=:0 wine start C:\MyUpdater.exe update=1 close=1
...
However I need to schedule this via cron under a normal user. I believe I should only start X only once (to maintain the correct headless DISPLAY=:0 ref).
I am a big fan of doing things right and am wondering on the correct way to set this up so X starts on boot but is accessible by the crontask.
A pointer would be greatly appreciated. Thanks in advance.
Lex

A: Start headless X on boot:
sudo /var/systemd/system/headlessx.service

With content:
[Unit]
Description=Headless X server
[Service]
ExecStart=/usr/bin/X
[Install]
WantedBy=multi-user.target
Then test/install:
Start it:
    sudo systemctl start headlessx
Enable it to run at boot:
    sudo systemctl enable headlessx
Stop it:
    sudo systemctl stop headlessx
Hope this helps someone. Running my windows GUI based app from the command line works a treat. Now if only I could make is work as a cron task life would be perfect. ;)


text:
Q: Image download with Python I'm trying to download images with Python 3.9.1
Other than the first 2-3 images, all images are 1 kb in size. How do I download all pictures? Please, help me.
Sample book: http://web2.anl.az:81/read/page.php?bibid=568450&pno=1
import urllib.request
import os

bibID = input("ID: ")
first = int(input("First page: "))
last  = int(input("Last page: "))

if not os.path.exists(bibID):
    os.makedirs(bibID)

for i in range(first,last+1):
    url=f"http://web2.anl.az:81/read/img.php?bibid={bibID}&pno={i}"
    urllib.request.urlretrieve(url,f"{bibID}/{i}.jpg")

A: Doesn't look like there is an issue with your script. It has to do with the APIs you are hitting and the sequence required.
A GET http://web2.anl.az:81/read/img.php?bibid=568450&pno=<page> just on its own doesn't seem to work right away. Instead, it returns No FILE HERE

The reason this happens is that the retrieval of the images is linked to your cookie. You first need to initiate your read session that's generated when first visiting the page and clicking the TƏSDİQLƏYIRƏM button
From what I could tell you need to do the following:

*

*POST http://web2.anl.az:81/read/page.php?bibid=568450 with Content-Type: multipart/form-data body. It should have a single key value of approve: TƏSDİQLƏYIRƏM - this starts a session and generates a cookie for you which you have to add as a header for all of your API calls from now on.
E.g.

requests.post('http://web2.anl.az:81/read/page.php?bibid=568450', files=dict(approve='TƏSDİQLƏYIRƏM'))

*Do the following in your for-loop of pages:
a. GET http://web2.anl.az:81/read/page.php?bibid=568450&pno=<page number> - page won't show up if you don't do this first
b. GET http://web2.anl.az:81/read/img.php?bibid=568450&pno=<page number> - finally get the image!


text:
Q: how can I implement pagination in flutter firebase listview project? I Implement a list view using stream builder. Now my apps load all the data from firebase. but I want to load first time only 20 item After when user scroll down then it is loaded another 20 item. That means I want to load 20 item per page. So Now How I implement paging in my existing code? Here is the code.
``
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:contackbook/src/model/dactor_model.dart';
import 'package:contackbook/src/model/data.dart';
import 'package:contackbook/src/theme/extention.dart';
import 'package:contackbook/src/theme/light_color.dart';
import 'package:contackbook/src/theme/text_styles.dart';
import 'package:contackbook/src/theme/theme.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_image/firebase_image.dart';
import 'home_page.dart';
import 'detail_page.dart';

class Company {
  int id;
  String name;

  Company(this.id, this.name);

  static List<Company> getCompanies() {
    return <Company>[
      Company(1, 'Md. '),
      Company(2, 'Engr.'),
      Company(3, 'Engr. Md. '),
      Company(4, 'Dr. '),
      Company(5, 'Dr. Md. '),
      Company(5, 'Dr. Engr. Md. '),
    ];
  }
}

class EmployeeList extends StatefulWidget {
  EmployeeList({Key key}) : super(key: key);

  @override
  _EmployeeListState createState() => _EmployeeListState();
}
Widget _appBar() {
  BuildContext context;
  return AppBar(
    elevation: 0,
    backgroundColor: Theme.of(context).backgroundColor,
    title: Center(child: const Text('বাপবিবোর্ড ফোনবুক', style: TextStyle(color: Colors.black),)),
    leading: RaisedButton(
      onPressed: () {
        Navigator.pop(context);
      },
      child: Icon(
        Icons.keyboard_backspace_rounded,
        size: 30,
        color: Colors.black,

      ),
    ),

    actions: <Widget>[
      ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(13)),
        child: Container(
          // height: 40,
          // width: 40,
          decoration: BoxDecoration(
            color: Theme.of(context).backgroundColor,
          ),
          child: Image.asset("assets/logo.png", fit: BoxFit.fill),

        ),
      ).p(8),
    ],
  );
}

String searchString;
class _EmployeeListState extends State<EmployeeList> {
  TextEditingController nameController = new TextEditingController();
  TextEditingController emailController = new TextEditingController();
  TextEditingController mobileController = new TextEditingController();
  TextEditingController mobileController1 = new TextEditingController();
  TextEditingController designationController = new TextEditingController();
  TextEditingController orgController = new TextEditingController();
  TextEditingController whatsappController = new TextEditingController();
  TextEditingController deptController = new TextEditingController();
  TextEditingController searchController = new TextEditingController();
  TextEditingController pabxController = new TextEditingController();
  TextEditingController addressController = new TextEditingController();
  TextEditingController faxController = new TextEditingController();
  TextEditingController officeController = new TextEditingController();
  TextEditingController titleController = new TextEditingController();
  List<Company> _companies = Company.getCompanies();
  List<DropdownMenuItem<Company>> _dropdownMenuItems;
  Company _selectedCompany;

  Widget _searchField() {
    return Container(
      height: 55,
      margin: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(13)),
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: LightColor.grey.withOpacity(.3),
            blurRadius: 15,
            offset: Offset(5, 5),
          )
        ],
      ),
      child: TextField(
        onChanged: (val){
          setState(() {
            searchString=val.toLowerCase();
          });
        },
        controller: searchController,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
          border: InputBorder.none,
          hintText: "brebapict(OrgDesigDept)",
          hintStyle: TextStyles.body.subTitleColor,
          suffixIcon: SizedBox(
              width: 50,
              child: Icon(Icons.search, color: LightColor.purple)
                  .alignCenter
                  .ripple(() {}, borderRadius: BorderRadius.circular(13))),
        ),
      ),
    );
  }
  @override
  void initState() {
    _dropdownMenuItems = buildDropdownMenuItems(_companies);
    _selectedCompany = _dropdownMenuItems[0].value;
    super.initState();
  }
  List<DropdownMenuItem<Company>> buildDropdownMenuItems(List companies) {
    List<DropdownMenuItem<Company>> items = List();
    for (Company company in companies) {
      items.add(
        DropdownMenuItem(
          value: company,
          child: Text(company.name),
        ),
      );
    }
    return items;
  }

  onChangeDropdownItem(Company selectedCompany) {
    setState(() {
      _selectedCompany = selectedCompany;

    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       // bottomNavigationBar: _searchField(),
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Theme.of(context).backgroundColor,
        title: Center(child: const Text('বাপবিবোর্ড ফোনবুক', style: TextStyle(color: Colors.black),)),
        leading: BackButton(color: Colors.black),
        actions: <Widget>[
          ClipRRect(
            //borderRadius: BorderRadius.all(Radius.circular(13)),
            child: Container(
              // height: 40,
              // width: 40,
              decoration: BoxDecoration(
                color: Theme.of(context).backgroundColor,
              ),
              child: Image.asset("assets/logo.png", fit: BoxFit.fill),

            ),
          ).p(8),
        ],
      ),
      body: Column(
        children: [
          _searchField(),
          Expanded(
            child: SizedBox(
                height: 200.0,
                child: BookList()),
          ),
        ],
      ),
    );
  }
}
String replaceWhitespaces(String s, String replace) {
  if (s == null) {
    return null;
  }

  return s.replaceAll(' ', replace);
}

class BookList extends StatelessWidget {
  TextEditingController nameController = new TextEditingController();
  TextEditingController emailController = new TextEditingController();
  TextEditingController mobileController = new TextEditingController();
  TextEditingController designationController = new TextEditingController();
  TextEditingController orgController = new TextEditingController();
  TextEditingController whatsappController = new TextEditingController();
  TextEditingController deptController = new TextEditingController();
  //String searchString;
  @override
  Widget build(BuildContext context) {

    //TODO: Retrive all records in collection from Firestore
    return StreamBuilder<QuerySnapshot>(
      stream: (searchString==null || searchString.trim()=='')?
      Firestore.instance.collection('ebook').orderBy('grade', descending: false).snapshots() : Firestore.instance.collection('ebook')
          .where('searchIndex',arrayContains: searchString ).limit(10)
          //.where('organization',isEqualTo: searchString )
          .snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

        if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return Center(
              child: CircularProgressIndicator(),
            );
          case ConnectionState.none:
            return Text('কোন ডাটা খুজে পাওয়া যায়নি !');
          case ConnectionState.done:
            return Text('আপনার চাহিত ডাটা খুজে পাওয়া গিয়েছে!');

          default:
            return new ListView(
              padding: EdgeInsets.only(bottom: 80),
              children:
                  snapshot.data.documents.map((DocumentSnapshot document) {
                return Padding(
                  padding: EdgeInsets.symmetric(vertical: 3, horizontal: 10),
                  child: Card(
                    color: Colors.white,
                    shape: RoundedRectangleBorder(
                      side: BorderSide(color: Colors.white70, width: 0.2),
                      borderRadius: BorderRadius.circular(10),
                    ),

                    margin: EdgeInsets.all(3.0),
                    child: ListTile(
                      leading: Icon(Icons.assignment_ind_rounded, size: 50, color: Colors.blueGrey[100],),

                      onTap: () {
                        Navigator.push(context, MaterialPageRoute(builder: (context) => DetailPage(document.documentID)));
                      },

                      title: new Text("\nনামঃ " + document['title'] +" "+ document['name'],style: TextStyle(
                        //using ARGB (Alpha Red Green Blue)
                        color: Colors.black87,
                        fontWeight: FontWeight.bold,
                        fontSize: 15,
                      ),),
                      subtitle: new Text("পদবিঃ " + document['designation'] +" " + document['postfix']+"\nপ্রতিষ্ঠানঃ "+ document['organization']+"\n"+"দপ্তর/পরিদপ্তর/শাখা/পবিসঃ "+ document['dept']+"\n",style: TextStyle(
                        //using ARGB (Alpha Red Green Blue)
                        color: Colors.purple[700],
                        fontWeight: FontWeight.bold,
                        fontSize: 13,

                      ),),
                      trailing:
                          // Delete Button
                          InkWell(
                        onTap: () {
                          //TODO: Firestore delete a record code
                        },

                        child: Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: 10, vertical: 10),
                          child: Icon(Icons.chevron_right_rounded,color: Colors.purple,),
                        ),
                      ),
                    ),
                  ),
                );
              }).toList(),

            );
        }
      },
    );
  }
}

``
Now help me how I implement paging with my existing flutter firebase code. I am new in flutter firebase, so please help me with code.


text:
Q: Lookup value in Query I'm trying to replace the local variables i've declared below to capture them in calculated columns.
So the [YTD] column would look up Today's Date - 1 and return the [FiscalDayOfYear] making everything in that column less than that "YTD" and anything greater "NA"
DECLARE @ytd FLOAT = 124
DECLARE @monthly FLOAT = 4

SELECT *
FROM(
 SELECT [Date]
      ,[FiscalDayOfYear]
      ,[FiscalYear]
      ,[FiscalMonthNumber]
      ,[FiscalWeekNumber]
      ,[YTD] = IIF([FiscalDayOfYear] <= @ytd, 'YTD','NA')
      ,[MTD] = IIF(([FiscalDayOfYear] <= @ytd) AND ([FiscalMonthNumber] = @monthly), 'MTD','NA')
  FROM [DL].[Date]
 WHERE  CONVERT(date,Date) >= '2018-01-01') AS DT
UNPIVOT
(
  [FLAG] FOR FLAGS IN ([YTD], [MTD])
) AS pivoted_tbl
WHERE [FLAG] != 'NA'

Because of our fiscal calendar I can't just use the Date column I've got to compare to day of year in our calendar.


text:
Q: Python error in VSCode :Sorry, something went wrong activating IntelliCode support for Python My code is not working in vscode when i click to run code i saw this error:

Sorry, something went wrong activating IntelliCode support for Python.
Please check the "Python" and "VS IntelliCode" output windows for
details.

and when i try to run code again i saw this message;

Code is already running

Code dont stop when i click to ctrl+c so i have to close the editor and open it back. I dont understand why this happen , please help me,thanks in advance.

A: I would just like to add a few helpful links:
Intellicode Issue 57
Intellicode Issue 266
Gitmemory issue 486082039
For a lot of people, it just began working after a few tries randomly. See this text (quoted from issue 57):

There's a race condition in the activation of both the IntelliCode and Python language server extensions. Even if the Python extension is loaded, the language server that the extension spins up might not be fully initialized yet. So if the Python extension loads, then the IntelliCode extension, then the Python language server initializes, we will have this problem.

For some people, it was working to reload VS Intellicode pack following the reinstall the Python extension pack.
Thank you.

A: Go to Extensions, then search for the Python extension, then switch to release.

A: *

*Make sure to have Pylance installed (intellisense support for Python)

*Make sure to be into the tab for any python file For VS Code, and locate the {} Python icon on the bottom row. Click over the {} icon, and then click over Select Interpreter. Just after that, make sure to input the desired python path, wait for a few seconds in the current python tab, and finally Pylance will be doing its job

A: *

*First of all find your Python installation path

*Copy it

Then in VSCode

*

*Open settings

*Extensions

*Python

*Default Interpreter Path

And paste the full path to your Python installation folder.
For example:
X:/Program Files/Python310

If it didn't work immediately, try reloading VSCode.
(P.S. Should work without any reloads)


text:
Q: Access ALSA as systemd system service running as a regular user I have a service which uses both the network and sound(ALSA), and I'm trying to make a systemd system service out of it. It works as a user service, but I can't make it work as a system service.
dbus-run-session[16623]: ALSA lib pulse.c:242:(pulse_connect) PulseAudio: Unable to connect:
dbus-run-session[16623]: Alsa error PCM open ALSA function 'snd_pcm_open' failed with error 'ECONNREFUSED: Connection refused'
dbus-run-session[16623]: Could not start audio: Alsa error: PCM open failed

Here's what I have so far. It's a template unit, the parameter is my user name.
Commented out the sandboxing settings.
# /etc/systemd/system/spotifyd@.service
[Unit]
Description=A spotify playing daemon
Documentation=https://github.com/Spotifyd/spotifyd
Wants=sound.target
After=sound.target
Wants=network-online.target
After=network-online.target

[Service]
User=%i

Type=exec
ExecStart=/usr/bin/dbus-run-session /usr/local/bin/spotifyd --no-daemon

Restart=always
RestartSec=12

ProtectSystem=full
#ProtectSystem=strict

#ProtectHome=tmpfs
#TemporaryFileSystem=/home/%i
#BindPaths=/home/%i/.config/pulse
#BindReadOnlyPaths=/home/%i/.local/share/

#ProtectHome=read-only
#ReadWritePaths=/home/%i/.config/pulse
#ReadOnlyPaths=/home/%i/.local/share/

#PrivateTmp=true
#NoNewPrivileges=true

[Install]
WantedBy=default.target

Comments:

*

*The daemon is not compiled with pulseaudio support, only ALSA. Not sure if that would matter.

*dbus-run-session is needed otherwise it fails at startup, since it register a d-bus name.

*I prefer it as a system service instead of a user one because I can depend on the network-online

*I'm running the service with my user, but could be a new user as well, as long as I have d-bus/MPRIS working

*I don't want to run PulseAudio/ALSA as a system service

*Group=audio didn't work

So what's wrong with the audio setup? I expected a system service switched to a regular account to have the same outcome as a user service.

A:
I expected a system service switched to a regular account to have the same outcome as a user service.

It can be, although one thing is not shared: the environment.
This was required to successfully access ALSA. (Source: https://askubuntu.com/questions/70560/why-am-i-getting-this-connection-to-pulseaudio-failed-error)
Environment=XDG_RUNTIME_DIR=/run/user/1000

Which makes me realize I should just run as an user service. The lifetime of the system service and the user session don't match.


text:
Q: OpenGL 3.3/4.1 on Mac OSX 10.9 using GLFW library I'm trying to use OpenGL 3.3/4.1 on my Mac OSX 10.9 now that its finally available.  I've been using the SuperBible 5 book and its examples to learn 3.3.  I just found out that its actually only running OpenGL 2.1 though for my examples when my vertex shader started refusing to compile.  I found that I need to get ahold of this GLFW library to do OpenGL windowing for me.  This library will allow me to use the 4.1 version of OpenGL that OSX is capable of running.  My question is does anybody have a static version of the Mac OSX 9 OpenGL library GLFW version 3.0.4 they can just send me?  It is kind of a real pain trying to build the library from scratch as because it involves installing CMake and then the library code and then trying to get it all to work together and compile.  I really only need the library so I can start getting OpenGL 3.3/4.1 to run.

A: If you have troubles with linker try to compile like this:
g++ youSource.cpp -I/usr/local/include -L/usr/local/lib -lglfw3 -framework Cocoa -framework OpenGL -framework IOKit -framework CoreFoundation -framework CoreVideo

or just:
g++ youSource.cpp -I/usr/local/include `pkg-config --cflags glfw3`  `pkg-config --static --libs glfw3`

A: I will suggest installing glfw via homebrew http://brew.sh/
The advantage being you can always uninstall it neatly by doing brew uninstall glfw3!
You need to have the "Command Line Tools for Xcode" and Xcode install https://github.com/Homebrew/homebrew/wiki/Installation
xcode-select --install
Once Homebrew is installed, open the terminal and run
brew update
brew tap homebrew/versions
brew install glfw3 for glfw3 OR
brew install glfw2 for glfw2
Also, if you desire an static build, use the flag --static
brew install --static glfw3
The libraries and include files will be available at usr/local/lib and usr/local/include
Now, if you have a program that relies in opengl and glfw, you'd want to compile it something like this:
gcc program.c -o myapp -framework OpenGl -lglfw3 (or -lglfw2)
If you still have some problems with the glfw header file, you can do:
gcc program.c -o myapp -framework OpenGl -I/usr/local/include -lglfw3

A: To build the GLFW library from source, only a few steps are required:

*

*Download and extract the GLFW source code.

*Open the Terminal.

*cd to the extracted directory.

*Type in cmake ., hit return.

*A Makefile will be created for you.

*Type in make, hit return.

*After the compilation process, type in sudo make install.
The libraries will be copied to /usr/local/lib/, the header files to /usr/local/include/.
Note: You'll need a compiler suite installed to build software, this would usually be the XCode Command Line Tools package. For this, install and launch XCode from the Store or download the tools from the developer site.


text:
Q: remove newlines in file between every newlines below is the part of file which has zimbra accounts listed(500+) separated by an empty newline
cn: Jack
displayName: Jack Johnson
givenName: Jack
sn: johnson
zimbraMailDeliveryAddress: Jack@example.com

cn: james ryan
displayName: James Ryan
givenName: James
sn: Ryan
zimbraMailDeliveryAddress: James@example.com

....

I want to have the file with the content like below so that i can import them to new server using zmprove
cn: Jack displayName: Jack Johnson givenName: Jack sn: johnson zimbraMailDeliveryAddress: Jack@example.com
cn: james ryan displayName: James Ryan givenName: James sn: Ryan zimbraMailDeliveryAddress: James@example.com

i tried writing the script without removing new lines but couldnt extract so far
for line in `cat /tmp/account3.txt`;
do
    echo $line | grep "zimbraMailDeliveryAddress:" > /dev/null
    RESULT=$?

        if [ $RESULT -eq 0 ];  then
    email=`echo $line | cut -d' ' -f2`  > /dev/null
    continue

    elif   echo $line | grep "sn:"   > /dev/null
    RESULT=$?
    if [ $RESULT -eq 0 ];  then
    sn=`echo $line | awk '{ print $2; }'`  > /dev/null
    continue

        elif  echo $line | grep "givenName:"  > /dev/null
    RESULT=$?
    if [ $RESULT -eq 0 ];  then
    givenName=`echo $line | awk '{ print $2; }'`  > /dev/null
        continue

    elif  echo $line | grep "displayName:"  > /dev/null
    RESULT=$?
    if [ $RESULT -eq 0 ];  then
    displayName=`echo $line | awk '{ print $2; }'`  > /dev/null
        continue

        elif echo $line | grep "cn:" > /dev/null
    RESULT=$?
    if [ $RESULT -eq 0 ];  then
    cn=`echo $line | cut -d' ' -f2`  > /dev/null
        continue
    fi
        else
          :
    fi
        echo $email $sn $cn $displayName $givenName
done
# awk '/cn:|displayName:|givenName:|sn:|zimbraMailDeliveryAddress:/{printf "%s ", $0; next} 1' /tmp/account2.txt

A: $ awk -v RS= '{$1=$1}1' file
cn: Jack displayName: Jack Johnson givenName: Jack sn: johnson zimbraMailDeliveryAddress: Jack@example.com
cn: james ryan displayName: James Ryan givenName: James sn: Ryan zimbraMailDeliveryAddress: James@example.com

A: awk can handle this easily with empty RS:
awk -v RS= '{gsub(/\n/, " ")} 1' file

cn: Jack displayName: Jack Johnson givenName: Jack sn: johnson zimbraMailDeliveryAddress: Jack@example.com
cn: james ryan displayName: James Ryan givenName: James sn: Ryan zimbraMailDeliveryAddress: James@example.com

By using RS= we are splitting input data on records when we get an empty line after zimbraMailDeliveryAddress lines.

A: This might work for you (GNU sed):
sed ':a;N;/\n\s*$/!s/\s*\n/ /;ta;s/\n//p;d' file

Read two or more lines into the pattern space (PS) replacing zero or spaces followed by a newline with a space if the last line read is not an empty line. If the last line read is empty, remove it and print the lines in the PS and then delete the PS.
N.B. This also caters for the last empty line not being present.
If the format of the file is fixed as in the example text:
 sed 'N;N;N;N;N;s/\s*\n/ /g;s/ $//' file

may be suffice.

A: My awk solution would be:
awk 'BEGIN{RS="";FS="\n";}
      {
      for(i=1;i<=NF;i++)
        printf "%s%s", $i, (i<NF?OFS:ORS)
      }' file

Output
cn: Jack  displayName: Jack Johnson givenName: Jack sn: johnson zimbraMailDeliveryAddress: Jack@example.com
cn: james ryan displayName: James Ryan givenName: James sn: Ryan zimbraMailDeliveryAddress: James@example.com

A: Another way with sed :
sed '/^$/!{H;d};/^$/{x;G;s/\n/ /g;s/^ //}' file


text:
Q: Automating input in bash I have a bash script that runs a few psql commands. Every time a command is ran it prompts for user password. I'd like to make the script input the password automatically so I'd only need to run the script and not need to input anything.
I am aware that I can do this for psql
PGPASSWORD=root psql -h localhost -d $db_name -U root -c

but I'd like to know how to automate input in general/

A: You can export the PGPASSWORD as below:

*

*export PGPASSWORD=root

*psql -h localhost -d $db_name -U root -c


text:
Q: Increasing the limit on HTML element nesting in Firebug? I have a page with deeply-nested HTML elements generated from a framework. I would like to inspect it with Firebug.
At a certain depth Firebug no longer displays the element contents.
The simplest way to reproduce the issue is with this perl snippet. It will create 100 nested divs, with text every 10.
foreach $i (1 .. 100) {
  print "
\n";
  print $i if (0 == ($i % 10));
}
print "
\n" x 100;

Using Firebug to inspect the text "100", at div 96 instead of

  ... contents ...

there is only

Is it possible to increase the depth that Firebug can cope with?
Versions are Windows Firefox 7.0.1 with Firebug 1.8.3
The "inspect element" in Chrome works fine with this example, as does F12 inspection in Internet Explorer 8.

A: First things first, as mentioned in some comments already: what framework generates that kind of depth? :) Best try to solve that.
Back to your question, I would speculate the answer to your question is that the depth is determined by Firefox, not Firebug, and thus cannot be changed.
The FB addon is open source. I had never looked at it before, but glancing over this source file it seems the aria-expanded attribute is used to create trees. Speculating even more, based on this aria attribute I would guess that Firefox has that value-max set somewhere around 100.
Funny thing to note by the way, if I keep expanding in Firebug with the 'right' arrow key it does seem to expand all the way down to the 100th div: you can see this in the bar just above the html (and just below the {Console, Html, ...} bar). It's just the collapse/expand visualization that stops at some max depth.

A: Like the previous comment, I would suggest trying not to use that framework, or amending it.


text:
Q: Windows: How to take a Screenshot of a Window programmatically? I'm trying to use Windows APIs to take a screen shot of a window. Here is my current code:
//Grab the window
HWND window = me;//GetForegroundWindow();
HDC context = GetDC(window);
RECT windowRect;
GetWindowRect(window, &windowRect);
int w = windowRect.right-windowRect.left;
int h = windowRect.bottom-windowRect.top;

//Copy the data
for (int y=0;y<h;y++)
    for (int x=0;x<w;x++)
    {
        COLORREF color = GetPixel(context, x,y);
        std::cout<<color<<std::endl;
    }

The width and height return correctly (as well as the window location), but the color is always 0xFFFFFF (white).
It seems like it should be fairly easy as in windows taking a screenshot of a window is simply alt+shift+Print Screen


text:
Q: Android developments of packet routing and control I try to find a method for android devices to be routers as my goal is to control packets and even implement different routing algorithm. I don't know how does Android OS surport. As I knew, Android OS includes Wifi hotspot features. But the features are limited, there are no advance settings like routing table, firewall, ARP, NAT...
I also find some APP like "Droidwall" which can act as firewall for each application with root permission. It means there are some API for developer. Where can I find some resources(document or sample code) about the related developments? Which features could Android surport?

A: I finally used adb shell to make some Linux command. "DroidWall" can be implemented by using "iptables" command. I try to write an app where I can make some shell command when some events occurred . But I'm using shell command to control now.


text:
Q: Normalizing a multivalued column in a large table I'm having an issue converting the VBA code seen in this this post to an R-script.
The problem is as follows, I have a column (from a source database, not by choice) that contains multiple values for the attribute. I'd like to normalize this table and retain the order in which each value occurs in each cell.
An example dataset:
dat <- data.frame(
  ID = c(1:3),
  Multi = c("VAL1 VAL2 VAL3","VAL2 VAL3","VAL3 VAL1")
  ,stringsAsFactors=FALSE)

  ID          Multi
1  1 VAL1 VAL2 VAL3
2  2      VAL2 VAL3
3  3 VAL2 VAL3 VAL1

The pseudocode would be something like:

*

*Loop over each row

*Split string Multi with a space as a separator

*For each splitted string, append new row in a separate data.frame with the ID, Order within the total string and the value.

The result would look like:
      ID   Order    Multi
1      1       1     VAL1
2      1       2     VAL2
3      1       3     VAL3
4      2       1     VAL2
5      2       2     VAL3
6      3       1     VAL2
7      3       2     VAL3
8      3       3     VAL1

I'm currently looking at doing so with a data.frame, I'm thinking data.table would be more appropriate as my table will have approximately 400.000 of these rows.
I apologize for not having any code ready, I'm still contemplating whether I need to use the apply family, data.table or a simple for loop. I'll keep this post updated with any progress I make.

A: Here are a couple of ways...
In base R:
X <- setNames(strsplit(as.character(dat$Multi), " "), dat$ID)
X1 <- stack(X)
X1$order <- ave(X1$ind, X1$ind, FUN = seq_along)
X1
#   values ind order
# 1   VAL1   1     1
# 2   VAL2   1     2
# 3   VAL3   1     3
# 4   VAL2   2     1
# 5   VAL3   2     2
# 6   VAL2   3     1
# 7   VAL3   3     2
# 8   VAL1   3     3

OR (better):
X <- strsplit(as.character(dat[, "Multi"]), " ", fixed = TRUE)
len <- vapply(X, length, 1L)
data.frame(ID = rep(dat[, "ID"], len), order = sequence(len),
           Multi = unlist(X, use.names=FALSE))

Using concat.split.multiple from my "splitstackshape" package (probably not too efficient on 400,000 rows though).
library(splitstackshape)
out <- concat.split.multiple(dat, "Multi", " ", "long")
out[order(out$ID, out$time), ]
#   ID time Multi
# 1  1    1  VAL1
# 4  1    2  VAL2
# 7  1    3  VAL3
# 2  2    1  VAL2
# 5  2    2  VAL3
# 8  2    3  <NA>
# 3  3    1  VAL2
# 6  3    2  VAL3
# 9  3    3  VAL1

And, since you requested "data.table":
library(data.table)
DT <- data.table(dat)
DTL <- DT[, list(unlist(strsplit(as.character(Multi), " "))), by = ID]
DTL[, order := sequence(.N), by = ID]
DTL
#    ID   V1 order
# 1:  1 VAL1     1
# 2:  1 VAL2     2
# 3:  1 VAL3     3
# 4:  2 VAL2     1
# 5:  2 VAL3     2
# 6:  3 VAL2     1
# 7:  3 VAL3     2
# 8:  3 VAL1     3

Update: Some timings
I didn't bother testing my "splitstackshape" approach, because that uses read.table under the hood, so I know it won't stand up to the demands of performance.
However, base R still seems to win out!
Sample "big" data:
dat_big <- do.call(rbind, replicate(floor(4000/3), dat, simplify = FALSE))
dat_big <- do.call(rbind, replicate(100, dat_big, simplify = FALSE))
dat_big$ID <- make.unique(as.character(dat_big$ID))

DT <- data.table(dat)
DT_big <- data.table(dat_big)

Functions to test:
fun1 <- function(inDF) {
  X <- strsplit(as.character(inDF[, "Multi"]), " ", fixed = TRUE)
  len <- vapply(X, length, 1L)
  data.frame(ID = rep(inDF[, "ID"], len), order = sequence(len),
             Multi = unlist(X, use.names=FALSE))
}

fun2 <- function(inDT) {
  DTL <- inDT[, list(unlist(strsplit(as.character(Multi), " ", fixed = TRUE))), by = ID]
  DTL[, order := sequence(.N), by = ID]
  DTL
}

The results for base R:
system.time(outDF <- fun1(dat_big))
#    user  system elapsed
#   6.418   0.000   6.454
dim(outDF)
# [1] 1066400       3
head(outDF)
#   ID order Multi
# 1  1     1  VAL1
# 2  1     2  VAL2
# 3  1     3  VAL3
# 4  2     1  VAL2
# 5  2     2  VAL3
# 6  3     1  VAL2
tail(outDF)
#               ID order Multi
# 1066395 1.133299     3  VAL3
# 1066396 2.133299     1  VAL2
# 1066397 2.133299     2  VAL3
# 1066398 3.133299     1  VAL2
# 1066399 3.133299     2  VAL3
# 1066400 3.133299     3  VAL1

The results for "data.table":
system.time(outDT <- fun2(DT_big))
#    user  system elapsed
#  14.035   0.000  14.057
dim(outDT)
# [1] 1066400       3
outDT
#                ID   V1 order
#       1:        1 VAL1     1
#       2:        1 VAL2     2
#       3:        1 VAL3     3
#       4:        2 VAL2     1
#       5:        2 VAL3     2
#      ---
# 1066396: 2.133299 VAL2     1
# 1066397: 2.133299 VAL3     2
# 1066398: 3.133299 VAL2     1
# 1066399: 3.133299 VAL3     2
# 1066400: 3.133299 VAL1     3


text:
Q: Creating executable in c++ which returns int array I want my C++ executable to return int array.
int* main()
{
    int a[]={1,2,3,4,5,6,7,8};
    return *a;
}

This will give error: '::main' must return 'int'.
Is there other way to do this?

A: You can not do this. The return type of the main function normally indicates only an error code. To output the result of some computation, write your array to a file.
For example:
#include <fstream>
int main()
{
    int a[]={1,2,3,4,5,6,7,8};
    std::ofstream ofs("data.tsv");
    for(int i=0; i<9; i++) {
        ofs << a[i] << "\t";
    }
    return 1;
}

A: In C++ main must indeed return an int. It is the error code of the program. 0 if everything went well, a positive number otherwise.
If you want to display an array of int. you can use <iostream>.
#include <iostream>

int main()
{
   int a[]={1,2,3,4,5,6,7,8};
   for (int i = 0; i < 9; i++)
       std::cout << a[i] << std::endl;
}

You can also choose to write to a file that is going to be read by another program.
#include <iostream>
#include <fstream>

int main()
{
   int a[]={1,2,3,4,5,6,7,8};
   ofstream myfile;
   myfile.open ("out.txt");
   for (int i = 0; i < 9; i++)
       myfile << a[i] << std::endl;
   myfile.close()
}

then in the other program
   std::vector<int> a;
   ifstream myfile;
   myfile.open ("out.txt");
   for (int i = 0; i < 9; i++)
   {
       int ai;
       myfile >> ai;
       a.push_back(ai);
   }
   myfile.close()

A: main is a special function and C++ standard is specific about its signature:
C++ Standard n3337 3.6.1

A program shall contain a global function called main, which is the
designated start of the program. It is implementation-defined whether
a program in a freestanding environment is required to define a main
function. [ Note: In a freestanding environment, start-up and
termination is implementation-defined; start- up contains the
execution of constructors for objects of namespace scope with static
storage duration; termination contains the execution of destructors
for objects with static storage duration. — end note ]
An
implementation shall not predefine the main function. This function
shall not be overloaded. It shall have a return type of type int, but
otherwise its type is implementation-defined. All implementations
shall allow both of the following definitions of main:
int main() { /*
...
*/ }
and
int main(int argc, char* argv[]) { /* ...
*/ }

Is there other way to do this?

Print to a file or display using stream:
int a[]={1,2,3,4,5,6,7,8};
for (int i = 0; i < 9; i++) {
    std::cout << a[i] << std::endl;
}

or:
#include <algorithm>

int a[]={1,2,3,4,5,6,7,8};
std::copy( a, a + 8, std::ostream_iterator<int>( std::cout,", "));

A: The error is very explicit. mainmust return an int, not an array. It is simply not possible.

A: There is no way of doing this. According to the C++ standard, main() has to return int.
See section 3.6.1.2 of the standard:

An implementation shall not predefine the main function.
     This function shall not be overloaded.
     It shall have a return type of type int, but otherwise its type is implementation-defined.

A: You cannot change the signature of the main method.  All code that invokes a process uses the same interface with a single int returned - how would you expect to retrieve these extra ints in whatever code is invoking the process?
However - if you need to combine multiple pieces of information, you can still encode them into a single int value.  For example you could interpret the decimal digits separately, allowing you to return ten or more values each taking values from 0-9.  Or for a different example, you may combine 32 binary flags to make up the integer value.  Whether this is useful depends on your use case.