text:
Q: Search specific letters in process name I have a problem in search process . I want to search specific letter in all running process with c#. for example my process have this process name(notepad,notepad++,note,calc,mspaint) and I want to search "note" ,Result search must be three item (notepad,notepad++,note) because only three process contain "note" . How programing ...
this code found only "notepad" and not found contain letter
Process[] pname = Process.GetProcessesByName("notepad");
                if (pname.Length == 0)
                {

                }
                else
                {
                    //some code if process found
                }

A: You can do something like this
    static void Main(string[] args)
    {
        Process.GetProcesses() //get all process
                     .Where(x => x.ProcessName.ToLower() // lower their names to lower cases
                                  .Contains("note")) //where their names contain note
                     .ToList() //convert to list
                     .ForEach(DoSomethingWithResults); //iterate over the items
    }

    private static void DoSomethingWithResults(Process obj)
    {
        //Do Something With Results
    }

A: First, loop through all the proccesses and then counter-match your desired string/phrase, either with Contains method or Equals.
Example :
Process[] processlist = Process.GetProcesses();

foreach (Process theprocess in processlist)
{
 if (theprocess.ProcessName.Contains("note")
  {

     ///Do your work here

  }
}

A: Another way of doing it would be
string searchText = "note";
List<Process> pfilteredProcess = Process.GetProcesses() // Get All Process
            .Where(p => p.ProcessName.ToLower() // Lower the name case of Process
            .Contains(searchText.ToLower()))   // Lower name of Search text
            .ToList();
//Work on the Searched List
        foreach (Process process in pfilteredProcess)
        {
            ///Do Activity
        }


text:
Q: How to format Home partition! A short time ago I installed Ubuntu alongside Windows.
A lot of things went wrong and I decided to reainstall Ubuntu on the partitions the old Ubuntu was using.
For this installation I created four different partitions: \, \home, \boot and swap, I indicated the old ubuntu partition to be the new home partition (maybe I didn't chose to format it).
Now when I turn on the PC, there are two ubuntus in the grub list, one which is functioning well (the latest) and one which is not functioning well (the earlier). I suppose the earlier ubuntu installation is still surviving in the \home partition.
Is it possible to format ONLY the home partition while keeping it structure (or format it and reinstall the structure without getting into new chaos)?
Some images
Image 1 - This is my partition list

Image 2 - This is what I get when I click "File system"

Image 3 - This is what I get when I click "home". It is different from my current home folder.

Image 4 - Inside there is another! "Home folder" which contains the folder Imagination3, the name of my profile on the old installation. It is the home folder of the old installation.

Image 5 - Returning to image 3, the Temitope folder is the home folder of the new installation, i.e. clicking on it bring me to my current home folder. Note that the new home folder is not equal to the partition \home. I'm trying to say: clicking on my current home folder doesn't open the media \home, but open \home\temitope.

So, what I need is to put an order in this home directory and partition issue, which I suppose implies eliminating the parasitic old installation, which should solve the grub entry issue.

A: Run gksu nautilus to get a file browser window with root access, then open /home, and select everything except your home directory ( and any other home directories if you have more than one user ) and delete it.  Hold down shift when pressing delete so it doesn't go to the trash bin, and then close the window when done.
You can run sudo update-grub to update the boot menu without the removed system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL: define the right indexes I have this table:
+---------------------+--------------+------+-----+---------+----------------+
| Field               | Type         | Null | Key | Default | Extra          |
+---------------------+--------------+------+-----+---------+----------------+
| ID                  | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| CODE                | varchar(255) | NO   |     | NULL    |                |
| REVISION            | varchar(255) | NO   |     | NULL    |                |
| NAME                | varchar(255) | NO   |     | NULL    |                |
+---------------------+--------------+------+-----+---------+----------------+

now, my app will perform these queries (from more likely to less likely):

*

*SELECT * FROM ITEM WHERE ID = ?

*SELECT * FROM ITEM WHERE CODE = ? ORDER BY REVISION DESC

*SELECT * FROM ITEM WHERE CODE = ? AND REVISION = ?

*SELECT * FROM ITEM WHERE CODE LIKE ? OR NAME LIKE ? ORDER BY CODE ASC, REVISION DESC
What is the best combination of indexes for such a scenario?
I'm using MySQL 5.6.14 (InnoDB) on Windows 8.1 x64.

UPDATE (still testing):
The best so far is using separate indexes: IDX_CODE (CODE), IDX_NAME (NAME).
mysql> describe select id, code, revision from UNIT where code like 'M0170SIGM1%' or name like 'M0170SIGM1%' ORDER BY code ASC, revision DESC;
+----+-------------+-------+-------------+-------------------+-------------------+---------+------+------+------------------------------------------------------------------+
| id | select_type | table | type        | possible_keys     | key               | key_len | ref  | rows | Extra                                                            |
+----+-------------+-------+-------------+-------------------+-------------------+---------+------+------+------------------------------------------------------------------+
|  1 | SIMPLE      | UNIT  | index_merge | IDX_CODE,IDX_NAME | IDX_CODE,IDX_NAME | 767,767 | NULL |   31 | Using sort_union(IDX_CODE,IDX_NAME); Using where; Using filesort |
+----+-------------+-------+-------------+-------------------+-------------------+---------+------+------+------------------------------------------------------------------+

No way to make MySQL use indexes in double direction sorting.

A: The primary key takes care of the first query.
For the second and third:  item(code, revision).  Note that the order by case asc is unnecessary because you are only choosing one code.
The last query is problematic.  You might want to use a full text index.  If the like attern is does not have a wild card at the beginning, then the following formulation might be better:
select i.*
from (select i.* from item i where code like ? union
      select i.* from item i where name like ?
     ) i
order by code, revision;

However, the engine is probably going to implement this query using full-table scan followed by a sort, regardless of the indexes.

A: For your fourth case with the mixed asc/desc order it might fail completely to use an index since mysql seems not to support this combination:
Order-By-Optimization in mysql

In some cases, MySQL cannot use indexes to resolve the ORDER BY,
  although it still uses indexes to find the rows that match the WHERE
  clause. These cases include the following:
...

You mix ASC and DESC:

SELECT * FROM t1 ORDER BY key_part1 DESC, key_part2 ASC;

Possible solution for that problem:
if your revision would be simply an positive integer, you could use another column with that value multiplied by -1, and order by this column DESC, which would allow you to use an index on those two columns, since they would have the same direction... works here like a charm with a timestamp column...


text:
Q: How to group sub menu's in ant design I am new to Ant design. Here, I am trying to a responsive navbar therefore I want to hide some items of my navbar based on breakpoints. For that intention, I need to group some submenu into a group in the menu. But when I do this by using div's my navbar layout drops horizontal to vertical.
My code is,
<Menu
      className={navbarClasses.join(" ")}
      mode="horizontal"
      style={{ padding: "5px", fontSize: "15px" }}
    >
      {/* <Item icon={<MenuOutlined />} /> */}
      <Item className="logo_bottom">

      </Item>

      <>
        <SubMenu title="Demos" style={{ marginTop: "14px" }}>
          <Item>

              Modern

          </Item>
          <Item>Classic</Item>
          <Item>Vintage</Item>
          <Item>Standard</Item>
          <Item>Minimal</Item>
          <Item>Trendy</Item>
          <Item>Elegant</Item>
        </SubMenu>
        <SubMenu key="smenu" title="Categories" style={{ marginTop: "14px" }}>
          <Item className="ant-dropdown-link">Fresh Vegetables</Item>
          <Item>Diet Nutrition</Item>
          <Item> Healthy Foods</Item>
          <Item> Grocery Items</Item>
          <Item> Beaf Steak</Item>
        </SubMenu>
        <SubMenu key="ssmenu" title="Dietary" style={{ marginTop: "14px" }}>
          <Item className="ant-dropdown-link"> Vegetarian</Item>
          <Item> Kakogenic</Item>
          <Item> Mediterranean</Item>
          <Item>Organic</Item>
        </SubMenu>
        <Item style={{ marginTop: "14px" }}>Search</Item>
        <SubMenu
          title="Pages"
          style={{ marginRight: "auto", marginTop: "14px" }}
        >
          <SubMenu title="Users">
            <Item>My Account</Item>
            <Item>Sign In</Item>
            <Item>Sign Up</Item>
          </SubMenu>
          <Item>FAQ About Us</Item>
          <Item>Privacy Policy</Item>
          <Item>Terms & Condition</Item>
          <Item>Contact Us</Item>
          <Item>Checkout</Item>
          <Item>404</Item>
        </SubMenu>
      </>

      <Item style={{ marginTop: "14px" }}>
        <Dropdown overlay={menu} trigger={["click"]}>
           e.preventDefault()}>

            English - EN <DownOutlined />

        </Dropdown>
      </Item>
      <Item style={{ marginTop: "14px" }}>
        <Button
          icon={<ShoppingCartOutlined style={{ fontSize: "20px" }} />}
          type="text"
          size="large"
        >
          Cart
        </Button>
      </Item>
      <Item style={{ marginTop: "14px" }}>
        <Button
          icon={<UserOutlined style={{ fontSize: "20px" }} />}
          type="text"
          shape="round"
        >
          Sign In
        </Button>
      </Item>
    </Menu>

so how to group those sub menus? Thanks in advance.


text:
Q: How to link Django 2.2.5 web framework to GitHub? I have created a repository on GitHub and logged into my account on Pycharm Django settings. Currently I haven't had any luck with the terminal commands. I don't know if this is the right way to do things?
Looks like I've tried commands that are for older versions of Django.
git init

A: I am assuming you're trying to upload your Django project onto Github, so these are the steps you can follow.
# initialize your project as a git repository.
git init
# this will add an origin, meaning, where the files will be uploaded.
git remote add origin https://github.com/<username>/repository-name.git
# this will add all the files to your working tree
git add .
# this will commit your code
git commit -m "Your message as to what you have changed in code"
# this will push the code to Github, on master branch.
git push origin master


text:
Q: How to correct the Send an HTTP request to SharePoint action failing when using Power Automate. Input string was not in correct format error I am creating a Power Automate Flow that is supposed to fire when a certain list item in a column on my SharePoint list changes.  I am trying to capture the previous value of that changed column value.  When I test it it is constantly failing on the Send an HTTP request to SharePoint action with the error of "Input string was not in a correct format".  I'm not sure what is wrong as I am putting the title of the list in the script correctly.  Any help with this would be appreciated.
Below is the raw inputs for the request.
{
    "host": {
        "connectionReferenceName": "shared_sharepointonline",
        "operationId": "HttpRequest"
    },
    "parameters": {
        "dataset": "https://xxx.sharepoint.com/sites/XXX",
        "parameters/method": "GET",
        "parameters/uri": "_api/web/lists/getByTitle('Engineering Project Requests')/items(35)/versions(568.0)"
    }
}

A: I have figured out what was the issue in my case. Power Automate Since Version token gives you "SinceVersionLabel" instead of "SinceVersionId".
Try replacing it in the code and put it there as an expression.
_api/web/lists/getByTitle('Engineering Project Requests')/items(@{triggerOutputs()?['body/ID']})/versions(@{outputs('Get_changes_for_an_item_or_a_file_(properties_only)')?['body/SinceVersionID']})


text:
Q: How to process a dictionary of strings in python I have a dictionary of values that follow this string pattern informationGain_$index$ and threshold_$index$. My goal is to retrieve the maximum informationGain_$index$ and threshold_$index$.
An example dictionary looks like so:
{'informationGain_0': 0.9949486404805016, 'threshold_0': 5.0, 'informationGain_1': 0.9757921620455572, 'threshold_1': 12.5, 'informationGain_2': 0.7272727272727273, 'threshold_2': 11.5, 'informationGain_3': 0.5509775004326937, 'threshold_3': 8.6, 'informationGain_4': 0.9838614413637048, 'threshold_4': 7.0, 'informationGain_5': 0.9512050593046015, 'threshold_5': 6.0, 'informationGain_6': 0.8013772106338303, 'threshold_6': 5.9, 'informationGain_7': 0.9182958340544896, 'threshold_7': 1.5, 'informationGain_8': 0.0, 'threshold_8': 9.0, 'informationGain_9': 0.6887218755408672, 'threshold_9': 7.8, 'informationGain_10': 0.9182958340544896, 'threshold_10': 2.1, 'informationGain_11': 0.0, 'threshold_11': 13.5}

I written code to generate the dataset.
def entropy_discretization(s):

    I = {}
    i = 0
    while(uniqueValue(s)):
        # Step 1: pick a threshold
        threshold = s['A'].iloc[0]

        # Step 2: Partititon the data set into two parttitions
        s1 = s[s['A'] < threshold]
        print("s1 after spitting")
        print(s1)
        print("******************")
        s2 = s[s['A'] >= threshold]
        print("s2 after spitting")
        print(s2)
        print("******************")

        # Step 3: calculate the information gain.
        informationGain = information_gain(s1,s2,s)
        I.update({f'informationGain_{i}':informationGain,f'threshold_{i}': threshold})
        print(f'added informationGain_{i}: {informationGain}, threshold_{i}: {threshold}')
        s = s[s['A'] != threshold]
        i += 1

    print(I)

Given the example dataset, the maximum information gain is associated with threshold_0 and informationGain_0. I would like to find a general way of identifying these key values pairs from the dataset. Is there a way to search the dictionary such that I can return informationGain_*,threshold_* such that informationGain_* == max?

A: Here is a solution using a custom key with max. It works even if the dictionary is not sorted. This is assuming the input dictionary is named d.
M = max((k for k in d if k.startswith('i')),
        key=lambda x: d[x])
T = f'threshold_{M.rsplit("_")[-1]}'
out = {M: d[M], T: d[T]}

Output:
{'informationGain_0': 0.9949486404805016, 'threshold_0': 5.0}

NB. I used a simple test on the dictionary keys to check those that start with i in order to identify the informationGain_X keys. If you have a more complex real life dictionary, you might want to update this to use a full match or any other way to make identification of the key non ambiguous.

A: I've also found a way of doing this. It just took a few tries
    n = int(((len(I)/2)-1))
    print("Calculating maximum threshold")
    print("*****************************")
    maxInformationGain = 0
    maxThreshold       = 0
    for i in range(0, n):
        if(I[f'informationGain_{i}'] > maxInformationGain):
            maxInformationGain = I[f'informationGain_{i}']
            maxThreshold       = I[f'threshold_{i}']

    print(f'maxThreshold: {maxThreshold}, maxInformationGain: {maxInformationGain}')

A: One way to do this is as follows:
assuming your dictionary name is d
informationGain_max = max(list(d.values())[::2])
threshold_max = max(list(d.values())[1::2])

this only works under the assumption that since python 3.6 standard dict maintains the order of insertions.

A: Lets make a list, and each member of that list should be a tuple or list that contains two elements: first the information gain, and then the threshold. We can sort this list with either the .sort() method of the list or by using the sorted() function. The last tuple of the sorted list will contain the values you seek. If you are also interested in the index of these values then add their index as a third element of the tuples.


text:
Q: How to add words from a text file to a dictionary depending on the name? So I have a text file which has the script of Act 1 from a Romeo and Juliet play and I want to count how many times someone says a word.
Here is the text: http://pastebin.com/X0gaxAPK
There are 3 people speaking in the text: Gregory, Sampson, and Abraham.
Basically I want to make 3 different dictionaries (if that's the best way to do it?) for each of the three speakers. Populate the dictionaries with the words the people say respectively, and then count how many times they say each word in the entire script.
How would I go about doing this? I think I can figure out the word count but I am a bit confused on how to separate who says what and put it into 3 different dictionaries for each person.
My output should look something like this (this is not correct but an example):
Gregory -
25: the
15: a
5: from
3: while
1: hello
etc

Where the number is the frequency of the word said in the file.
Right now I have code written that reads the text file, strips the punctuation, and compiles the text into a list. I also don't want to use any outside modules, I'd like to do it the old fashioned way to learn, thanks.
You don't have to post exact code, just explain what I need to do and hopefully I can figure it out. I'm using Python 3.

A: You don't want to be stripping the punctuation right away. The colon preceded by a new line is telling you where one person's quote begins and ends. This will be important so you know which dictionary to append the words in the given quote to. You will probably need some kind of if-else which appends to a different dictionary depending on who is currently speaking.

A: import collections
import string
c = collections.defaultdict(collections.Counter)
speaker = None

with open('/tmp/spam.txt') as f:
  for line in f:
    if not line.strip():
      # we're on an empty line, the last guy has finished blabbing
      speaker = None
      continue
    if line.count(' ') == 0 and line.strip().endswith(':'):
      # a new guy is talking now, you might want to refine this event
      speaker = line.strip()[:-1]
      continue
    c[speaker].update(x.strip(string.punctuation).lower() for x in line.split())

Example output:
In [1]: run /tmp/spam.py

In [2]: c.keys()
Out[2]: [None, 'Abraham', 'Gregory', 'Sampson']

In [3]: c['Gregory'].most_common(10)
Out[3]:
[('the', 7),
 ('thou', 6),
 ('to', 6),
 ('of', 4),
 ('and', 4),
 ('art', 3),
 ('is', 3),
 ('it', 3),
 ('no', 3),
 ('i', 3)]

A: Here is a naive implementation:
from collections import defaultdict

import nltk

def is_dialogue(line):
    # Add more rules to check if the
    # line is a dialogue or not
    if len(line) > 0 and line.find('[') == -1 and line.find(']') == -1:
        return True

def get_dialogues(filename, people_list):
    dialogues = defaultdict(list)
    people_list = map(lambda x: x+':', people_list)
    current_person = None
    with open(filename) as fin:
        for line in fin:
            current_line = line.strip().replace('\n','')
            if  current_line in people_list:
                current_person = current_line
            if (current_person is not None) and (current_line != current_person) and is_dialogue(current_line):
                dialogues[current_person].append(current_line)
    return dialogues

def get_word_counts(dialogues):
    word_counts = defaultdict(dict)
    for (person, dialogue_list) in dialogues.items():
        word_count = defaultdict(int)
        for dialogue in dialogue_list:
            for word in nltk.tokenize.word_tokenize(dialogue):
                word_count[word] += 1
        word_counts[person] = word_count
    return word_counts

if __name__ == '__main__':
    dialogues = get_dialogues('script.txt', ['Sampson', 'Gregory', 'Abraham'])
    word_counts = get_word_counts(dialogues)
    print word_counts


text:
Q: Live share prices for a side project Me and some of my friends would want to start a side project which we will work at our spare time. Here is our criteria
1) A challenging project which will teach us skills which has business value in the future.
2) A potential to make money from the project itself.
Quite obvious targets.
We are looking into the possibility to create a live price feed. We understand we cannot match the ones in the market now. But we are looking into the possibility to provide a feed which could at least provide a "live" feed, even though it cannot match the real time performance provided by the insane hardware and software resources the "biggies" could provide.
If we could host the feed in a website which can show prices even 5 minutes late, that could do.
The current skills pool is C++ and C#.
We have WPF, asp.net, silverlight skills for UI (UI doesn't matter much anyway)
The questions
1)How is it possible to get the raw price feeds for cheap(or free)?
2)Is it possible to do this idea at least as proof of concept(which means it might not have any commercial value) in a year by 3 developers working 20 hours a week?
3)Is there any information available in the internet to start with?
4)Is there any open source projects in this area?

A: OK, things might have changed but this is what I can tell from working in the business of providing that data (albeit several years ago):

*

*it doesn't come cheap

*delayed data is cheaper than live data (that's one big reason why most stock quotes you find on website tickers are delayed by 15 minutes to over an hour, the cost that way is radically lower)

*I can't see how you're going to create something new here as your plan seems to be to take a feed from a provider and just repost that through some other channel without doing anything with it. That's going to be a problem with most providers as they won't allow you to resell their data as is.

*There are unlikely to be open source projects about this as the data is proprietary and not publicly available (you might find some screen scrapers that steal data from a website listing prices, but those mechanisms are a) unreliable (those websites change regularly) and b) a violation of the terms of use of those websites

To provide a full service platform would likely take you more than 3 people and more than a year, but you could create the raw basics in less than that if your skills with your chosen tools are good enough.

If I were you I'd start by creating my own feed, using some trending algorithm seeded with maybe real stock data you pull from say Euronext or NYSE websites for start values. That way you simulate real data without having to buy it (of course it won't be at all accurate or reflecting reality, but it's going to be free and as a simulation it works fine).
Store the incoming feed data in some database and you have your dataset that's constantly getting new data points for you to work with.


text:
Q: How to use branded string as an index to a Record type My strings take a certain format so I often type them to be sure they are in a particular format. For example I check my strings are prefixed with foo. How can I use a branded string as an index to a record?
type Foo = string & { _fooBrand: undefined }
type T = Record<Foo, string>
const f = (a: T, b: Foo) => {
  const c = a[b] // Type 'Foo' cannot be used as an index type.
}

A: I managed to work this one out by creating some helper functions caked in conditional types. You can then use the helper functions get(), set(), keys(), values()
export const get = <T, K extends keyof T>(obj: T, key: K): RecordValue<T> | undefined =>
  (obj as any)[key] as RecordValue<T> | undefined

export const set = <T, K extends keyof T, V extends RecordValue<T>>(
  obj: T,
  key: K,
  value: V
): CheckRecordKeyValue<T, K, V> => ((obj as any)[key] = value as any)

export const keys = <T>(obj: T): RecordKey<T>[] => Object.keys(obj) as RecordKey<T>[]

export const values = <T>(obj: T): RecordValue<T>[] => Object.values(obj) as RecordValue<T>[]

export type RecordKey<T> = T extends Record<infer K, infer V> ? K : never
export type RecordValue<T> = T extends Record<infer K, infer V>
  ? K extends keyof T
    ? V
    : never
  : never
export type CheckRecordKeyValue<T, K, V> = T extends Record<infer K2, infer V2>
  ? K extends K2
    ? V extends V2
      ? undefined
      : never
    : never
  : never

code now becomes
type Foo = string & { _fooBrand: undefined }
type T = Record<Foo, string>
const f = (a: T, b: Foo) => {
  const c = get(a, b) //
  set(a, b, 'asdf')
}


text:
Q: Implement LINQ to SQL expressions for a database with custom date/time format I'm working with an MS-SQL database with tables that use a customized date/time format stored as an integer. The format maintains time order, but is not one-to-one with ticks. Simple conversions are possible from the custom format to hours / days / months / etc. - for example, I could derive the month with the SQL statement:
SELECT ((CustomDateInt / 60 / 60 / 24) % 13) AS Month FROM HistoryData

From these tables, I need to generate reports, and I'd like to do this using LINQ-to-SQL. I'd like to have the ability to choose from a variety of grouping methods based on these dates (by month / by year / etc.).
I'd prefer to use the group command in LINQ that targets one of these grouping methods. For performance, I would like the grouping to be performed in the database, rather than pulling all my data into POCO objects first and then custom-grouping them afterwords. For example:
var results = from row in myHistoryDataContext.HistoryData
              group row by CustomDate.GetMonth(row.CustomDateInt) into grouping
              select new int?[] { grouping.Key , grouping.Count() }

How do I implement my grouping functions (like CustomDate.GetMonth) so that they will be transformed into SQL commands automatically and performed in the database? Do I need to provide them as Func<int, int> objects or Expression<> objects, or by some other means?

A: You can't write a method and expect L2S to automatically know how to take your method and translate it to SQL.  L2S knows about some of the more common methods provided as part of the .NET framework for primitive types.  Anything beyond that and it will not know how to perform the translation.
If you have to keep your db model as is:
You can define methods for interacting with the custom format and use them in queries.  However, you'll have to help L2S with the translation.  To do this, you would look for calls to your methods in the expression tree generated for your query and replace them with an implementation L2S can translate.  One way to do this is to provide a proxy IQueryProvider implementation that inspects the expression tree for a given query and performs the replacement before passing it off to the L2S IQueryProvider for translation and execution.  The expression tree L2S will see can be translated to SQL because it only contains the simple arithmetic operations used in the definitions of your methods.
If you have the option to change your db model:
You might be better off using a standard DateTime column type for your data.  Then your could model the column as System.DateTime and use its methods (which L2S understands).  You could achieve this by modifying the table itself or providing a view that performs the conversion and having L2S interact with the view.
Update:
Since you need to keep your current model, you'll want to translate your methods for L2S.  Our objective is to replace calls to some specific methods in a L2S query with a lambda L2S can translate.  All other calls to these methods will of course execute normally.  Here's an example of one way you could do that...
static class DateUtils
{
    public static readonly Expression<Func<int, int>> GetMonthExpression = t => (t / 60 / 60 / 24) % 13;
    static readonly Func<int, int> GetMonthFunction;

    static DateUtils()
    {
        GetMonthFunction = GetMonthExpression.Compile();
    }

    public static int GetMonth(int t)
    {
        return GetMonthFunction(t);
    }
}

Here we have a class that defines a lambda expression for getting the month from an integer time.  To avoid defining the math twice, you could compile the expression and then invoke it from your GetMonth method as shown here.  Alternatively, you could take the body of the lambda and copy it into the body of the GetMonth method.  That would skip the runtime compilation of the expression and likely execute faster -- up to you which you prefer.
Notice that the signature of the GetMonthExpression lambda matches the GetMonth method exactly.  Next we'll inspect the query expression using System.Linq.Expressions.ExpressionVisitor, find calls to GetMonth, and replace them with our lambda, having substituted t with the value of the first argument to GetMonth.
class DateUtilMethodCallExpander : ExpressionVisitor
{
    protected override Expression VisitMethodCall(MethodCallExpression node)
    {
        LambdaExpression Substitution = null;

        //check if the method call is one we should replace
        if(node.Method.DeclaringType == typeof(DateUtils))
        {
            switch(node.Method.Name)
            {
                case "GetMonth": Substitution = DateUtils.GetMonthExpression;
            }
        }

        if(Substitution != null)
        {
            //we'd like to replace the method call; we'll need to wire up the method call arguments to the parameters of the lambda
            var Replacement = new LambdaParameterSubstitution(Substitution.Parameters, node.Arguments).Visit(Substitution.Body);
            return Replacement;
        }

        return base.VisitMethodCall(node);
    }
}

class LambdaParameterSubstitution : ExpressionVisitor
{
    ParameterExpression[] Parameters;
    Expression[] Replacements;

    public LambdaParameterExpressionVisitor(ParameterExpression[] parameters, Expression[] replacements)
    {
        Parameters = parameters;
        Replacements = replacements;
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        //see if the parameter is one we should replace
        int p = Array.IndexOf(Parameters, node);
        if(p >= 0)
        {
            return Replacements[p];
        }

        return base.VisitParameter(node);
    }
}

The first class here will visit the query expression tree and find references to GetMonth (or any other method requiring substitution) and replace the method call.  The replacement is provided in part by the second class, which inspects a given lambda expression and replaces references to its parameters.
Having transformed the query expression, L2S will never see calls to your methods, and it can now execute the query as expected.
In order to intercept the query before it hits L2S in a convenient way, you can create your own IQueryable provider that is used as a proxy in front of L2S.  You would perform the above replacements in your implementation of Execute and then pass the new query expression to the L2S provider.

A: I think you can register your custom function in the DataContext and use it in the linq query. In this post is very well explained: http://msdn.microsoft.com/en-us/library/bb399416.aspx
Hope it helps.

A: Found a reference to some existing code which implements an IQueryable provider as Michael suggests.
http://tomasp.net/blog/linq-expand.aspx
I think assuming that code works, the other lingering issue is that you would have to have an Expression property for each type which contained the date.
The resulting code for avoiding doing that appears to be a bit cumbersome (though it would avoid the sort of errors you're trying to avoid by putting the calculation in a method):
Group Expression:
group row by CustomDate.GetMonth(row, x => x.customdate).Compile().Invoke(row)

Method to Return Group Expression:
public class CustomDate
{
        public static Expression<Func<TEntity, int>> GetMonth<TEntity>(TEntity entity, Func<TEntity, int> func)
        {
            return x => ((func.Invoke(entity)/60/60/24)%13);
        }
}

I'm not entirely sure whether that nested .Invoke would cause problems with the Expandable expression or whether the concept would have to be tweaked a bit more, but that code seems to supply an alternative to building a custom IQueryProvider for simple mathematical expressions.

A: There doesn't appear to be any way to instruct LINQ-to-SQL to call your SQL UDF. However, I believe you can encapsulate a reusable C# implementation in System.Linq.Expressions.Expression trees...
public class CustomDate {
    public static readonly Expression<Func<int, int>> GetMonth =
                customDateInt => (customDateInt / 60 / 60 / 24) % 13;
}

var results = from row in myHistoryDataContext.HistoryData
              group row by CustomDate.GetMonth(row.CustomDateInt) into grouping
              select new int?[] { grouping.Key , grouping.Count() }


text:
Q: AnyChart Template: How can I set the colour of a column only once? I am using AnyChart and am trying to set the chart to have green and Red columns. Right now I have to set the colour on every column. Is there a way to set it for all?
What I am doing:
var data = anychart.data.set([
                ["04/24/2022", 2, 6, "#ab0000", "#009933"],
                ["04/25/2022", 3, 4, "#ab0000", "#009933"],
                ["04/26/2022", 4, 2, "#ab0000", "#009933"],
                ["04/27/2022", 5, 2, "#ab0000", "#009933"],
                ["04/28/2022", 5, 2, "#ab0000", "#009933"]
            ]);

Complete Code:

<!DOCTYPE html>

    <title>JavaScript Bar Chart</title>

            html, body, #container {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            }

I am looking for a way to not need to copy the colours over and over. Does anyone know how I could format the fill colour to be only in the column data?

A: There is a way to solve your problem with AnyChart.
You can preconfigure colors with AnyChart Palettes.
// apply a palette to a chart
chart.palette(["#ab0000", "#009933"]);

Feel free to explore how to apply palettes in the playground.


text:
Q: How to correctly address "ALERT: Iterations finished, maximum likelihood not found" in poLCA? I intend to use Latent Class Analysis on a large dataset with 12 response categories and approximately 50,000 observations.  I am getting an "ALERT: Iterations finished, maximum likelihood not found" warning when I fit models with more than two latent classes.  Can I conclude that the models beyond two classes are poorly identified as the log-likelihood is not exactly same? The model is fit with nrep = 20 and maxiter = 150 and most repetitions across all classes greater than two result in llik values which are in the range of [..,-243389.9, -243358.4, -243269.5, -243259.4, -243269.7,...].
I found contradicting information online and the reference textbook: In this tutorial, they choose the models with 3 classes despite the said alert and in Collins, L. & Lanza, S. (2010) (page 95) they do not pick the 6 class model as the ML solution did not converge.  How seriously should I take this alert?
Any insights will help.

A: Increasing the number of maximum iterations (maxiter) solved the problem.  This is because the number of iterations required increases as the number of latent classes increase.


text:
Q: %%G from For Loop changing from index to %G using I am trying to write a batch file to automate some routine Matlab processes. The batch file loops through from 0 to a set value (usually between 50 and 75) using the For /L structure. The script copies the main Matlab script to the subfolder and runs it. The batch would normally continue onward so I put a :loop to wait until the Matlab ends.
echo off
setlocal EnableDelayedExpansion

REM The format is matlab_auto.in (max value).
For /L %%G in (0,1,%1) do (
REM Sanity check
echo 1 %%G

REM Create Outputs folder if non-existent
if not exist Outputs md Outputs

REM Copy .m file into deg folder and cd to folder
copy values_calc.m %%Gsort\values_calc.m
cd %%Gsort
echo Got to folder

    REM Running .m script and sanity check
echo 2 %%G
matlab -nosplash -nodesktop -noFigureWindows -logfile output.log -r "run('values_calc.m');"
echo 3 %%G

REM Waiting for matlab to finish
:loop
tasklist /fi "imagename eq MATLAB.exe" |find ":" > nul
echo 4 %%G
if errorlevel 1 goto loop
echo Finished Matlab
echo 5 %%G

REM Copy .m outputs into outputs folder, ignoring confirmation
copy Output_*.* ..\Outputs /Y
echo Copied outputs

REM Sanity check and return home
echo 6 %%G
cd %~dp0
echo Home again

)
The problem I'm having is that when it ends after the first iteration of the For loop. Echo 1, 2, 3 are 0. Echo 4 shows 0 the first time through :loop but then it shows %G for the remainder of the loops and at Echos 5 and 6. It also does not continue into further iterations of the For loop. I'm assuming this is because %%G is no longer a number (or in the range specified).
I have tried implementing a call subroutine to use the goto outside the loop but then it opens the Matlab dozens of times, crashing the computer.
Any insight or advice is appreciated. Thank you.
EDIT: Changed the :: for commenting to REM. It did not resolve this issue but looks better.
EDIT 2: I have a test case that demonstrates the problem. Its something with the :loop or goto.
    echo off
    setlocal EnableDelayedExpansion
for /l %%G in (0,1,5) do (
    :loop
    echo %%G
    pause
    if %%G==0 goto loop
)

A: Yes. The execution of a GOTO command cancel any active (pending) FOR or IF commands that may be nested inside parentheses at any level. This way, the commands placed below the :loop label are executed inside the FOR context the first time, but after the goto command they are executed as if they were placed outside the FOR loop! The way to solve this problem is extracting the code below the label into a subroutine and then call :loop in the FOR.
echo off
setlocal EnableDelayedExpansion

REM The format is matlab_auto.in (max value).
For /L %%G in (0,1,%1) do (
   REM Sanity check
   echo 1 %%G

   REM Create Outputs folder if non-existent
   if not exist Outputs md Outputs

   REM Copy .m file into deg folder and cd to folder
   copy values_calc.m %%Gsort\values_calc.m
   cd %%Gsort
   echo Got to folder

   REM Running .m script and sanity check
   echo 2 %%G
   matlab -nosplash -nodesktop -noFigureWindows -logfile output.log -r "run('values_calc.m');"
   echo 3 %%G

   REM Waiting for matlab to finish
   call :loop
   echo Finished Matlab
   echo 5 %%G

   REM Copy .m outputs into outputs folder, ignoring confirmation
   copy Output_*.* ..\Outputs /Y
   echo Copied outputs

   REM Sanity check and return home
   echo 6 %%G
   cd %~dp0
   echo Home again

)
goto :EOF

:loop
tasklist /fi "imagename eq MATLAB.exe" |find ":" > nul
REM echo 4 %%G
if errorlevel 1 goto loop
exit /B


text:
Q: Shutdown after N invalid attempts (lockscreen + tty) I've seen this question on AskUbuntu about monitoring lockscreen. However, imagine having an encrypted drive + home partition. Both are mounted and available while you are logged in.
The thing is, afaik, the number of attempts is not limited. How can I listen to unsuccessful attempts and after N tries just shut down the machine so I can prevent any further action that might target my storage via naive dictionary attack (e.g. friend/visit/...) on the lock screen?
Is there also any way for listening to unsuccessful attempts via tty? For example if someone tries to log in via tty1 twice and tty2 once (i.e. sum of all attempts 3), shutdown the machine too?

A: There are several PAM modules which can limit the number of attempts over time, e.g. pam_tally2 is available on most Linux distributions.
You can also create custom PAM modules, either in C or by using pam_exec to run custom shellscripts. For example, if the PAM stack looks like this:
(...)
auth [success=1 new_authtok_reqd=ok default=bad] pam_unix.so
auth optional pam_exec.so /usr/local/bin/count-or-shutdown.sh
(...)

then every successful password entry will skip over the pam_exec line, but every failed login will execute it.


text:
Q: Css onclick change class I want to change a class when I click.
The class is icon icon_plus, and when i click i want that class to be icon icon_minus-06and if click again back tothe original
My HTML code

My javascript code :

I am very weak with javascript
Thanks for the help.

A: Try to write toggleClass like this,
$("#icon").toggleClass("icon_plus icon_minus-06");

Since you are keeping icon class as a static one.
DEMO
Also as a side note, try to wrap your code inside document's ready handler. Since the selector would fail, if you keep your script inside header tag. But If you have placed your script in the end of body tag, then no issues. Anyway its better to use document's ready handler as it would make the code more procedural.
The code should be like this,
(function(){
  function ontop() {
    $("#icon").toggleClass("icon_plus icon_minus-06");
  }
  $(function(){
    $("a.top-bar-trigger").click(ontop);
  });
})();

A: You can solve this problem in two ways.
1) Using AddClass & RemoveClass Methods
    $("a.top-bar-trigger").click(changeClass);

    function changeClass() {
        if($("#icon").hasClass('icon_plus')){
            $("#icon").removeClass("icon_plus").addClass("icon_minus-06");
        }
        else{
            $("#icon").removeClass("icon_minus-06").addClass("icon_plus");
        }
    }

2) Using ToggleClass
    $("a.top-bar-trigger").click(changeClass);

    function changeClass() {
       $("#icon").toggleClass("icon_plus icon_minus-06");
    }

You can check the JSFiddle Links here
1) https://jsfiddle.net/4vzsn4kt/
2) https://jsfiddle.net/zzq820eu/

A: You can try this way:
$("a.top-bar-trigger").click(function(){
    $(".icon").toggleClass("icon_minus-06");
});

Fiddle: https://jsfiddle.net/5au3ywmz/2/

A: PROBLEM SOLVED
The code you have works if its run after the DOM is ready, you can see it working here: jsfiddle.net/hosw2wc9 – Adam Konieska


text:
Q: grep-friendly logging of stack traces I do a lot of grepping through logs generated by Java's Log4j and Python's logging module. Both create stack traces that include newline characters, causing the log entry to span multiple lines. This makes things hard to find with grep and violates the conventional log file formatting rules (one entry per line).
If I find something interesting in the stack trace, I have to open entire the log file (which can be very large) and browse to the line grep found, then scroll up to find the start of the log entry. This feels kludgey.
Is there a better way to handle this? Perhaps removing newline characters from stack traces somehow?
Thanks for any suggestions!

A:  grep 'your expressing and file name' | less

This will show you small stack first. Then enter to learn more.
You could also do 'head' or 'tail' of file name
  tail -1000 'filename'

This shows last(tail) 1000 lines from that file.

A: If you have GNU grep you can use the -C (AKA --context) switch:

-C NUM, --context=NUM
  Print NUM lines of output context.  Places a line containing -- between
  contiguous groups of matches.

I'm not sure if -C is part of POSIX grep but it is worth a shot.


text:
Q: swap fails in case of int and works in case of string #include <iostream>
#include <string>
#include <algorithm>
int main()
{
 std::string str1 = "good", str2 = "luck";
 swap(str1,str2); /*Line A*/
 int x = 5, y= 3;
 swap(x,y); /*Line B*/
}

If I comment Line B the code compiles(http://www.ideone.com/hbHwf) whereas commenting Line A the code fails to compile(http://www.ideone.com/odHka) and I get the following error:
error: 'swap' was not declared in this scope

Why don't I get any error in the first case?

A: swap(str1, str2) works because of Argument dependent lookup
P.S: Pitfalls of ADL

A: You're not qualifying swap; it works when passing in std::string objects because of ADL, but as int does not reside in namespace std you must fully qualify the call:
std::swap(x, y);

or use a using declaration:
using std::swap;
swap(x, y);

A: strings are in the std:: namespace, so the compiler looks for swap() for strings there. ints are not, so it doesn't. You want:
std::swap(x,y);

A: In both cases you should be using std::swap() instead of swap().


text:
Q: How to migrate from TortiseSVN to an Eclipse plugin to manage an established SVN project I have been working with the same Subversion working copy as a sub-directory of my local server's htdocs folder for months now. I was working in PHPDesigner7 and managing my repository with TortiseSVN. As I am the only one working, I just commit and keep working without any real need for multiple checkouts or updates.
I recently moved from PHPDesigner7 to Eclipse for my every day IDE.  I have created a project and used my working copy root as the location. I have been writing all my code in eclipse for about six weeks now, and it seems like it would be much easier to do SVN operations within the IDE. I want to start integrating SVN into my Eclipse workflow, but I want to keep my working copy in the same place it has been. There are a lot of files like Adobe Bridge index files and Docblox configuration files that I do not keep under source control, but are still important to my tools. If I create a new checkout these files will not be present. I also like being able to do local server testing directly from my working copy.
How can I use my existing working copy from within the Eclipse IDE? I have installed Subclipse, but I set my eclipse project up before I decided to try switching SVN management to the IDE. Is it as simple as making my workspace the same as the working copy? I have just been using the Eclipse default workspace. Would I be better off with a fresh Eclipse project? Are there any caveats I need to be aware of when moving from Tortise to Subclipse? I especially wonder if Subclipse does many small commit operations, or if I can continue making fewer heavily commented larger commits? Does anyone prefer the subversive plugin? If so why?

A: The root directory of your eclipse project should be the root of your working copy. Then you just have to right-click on the project and choose Team - Share Project, and follow the tutorial. At some point Eclipse will ask you if you want to keep the existing .svn files or not. Just choose to keep them.
The workflow in Eclipse is exactly the same as with any other SVN client. You update and commit when you want to. And you may also continue using TortoiseSVN to perform your SVN operations if you prefer. You'll just have to refresh your eclipse project after each operation.


text:
Q: jquery Datatables - how to achieve Server side fetching and Client side sorting I am using the datatables plugin for processing our tables.
We have this use case where we need to fetch the data (paginated)through an ajax call using bServerSide and sAjaxSource but would like to just sort the data on that page rather than fetching the sorted data from the server, as in our case this read would be very expensive.
Is it possible to do it? If yes, please suggest how to proceed.
Thanks in advance!!

A: I've read this discussion that might help you: basically you must inizialize de table with these options;
"bServerSide" : false,
"sAjaxSource" : "path to your ajax source"

In this way, the data get loaded only once and all the filtering is done by the client.
Than if you want to load more data you can use fnReloadAjax. You can read this discussion about the topic, i think it has all the answers you need.
EDIT - With pipeline you can avoid making frequent calls to the server for pagination only (if you filter data a call is made to the server).
If you want to get the data to the server only once and then filter data clientside you must disable server side processing  (white the above options set). If you disable server-side processing you can provide the user a way to get additional data from the server with "fnReloadAjax" (for example a button).
What i still don't get, do you need to get some other data from the server or whatever the user gets first is ok?
EDIT 2 - if you don't wan't to call the server, you can avoid using AJAX at all by enhancing an existing table. Just create the html servers side like this:

            col1
            col2
            col3

    <?php
    foreach ($rows as $row){
    //echo all rows here (be careful as for each row you must
    //have as many  as the column: no colspan!
    }
    ?>

And then create your datatable like this for example
oTable = $('.tablesorter').dataTable({
        "aaSorting": [[2, "asc"]],
        "bAutoWidth": false,
        "bFilter": false,
        "sDom": 'T<"clear">lfrtip',
        "aoColumns": [
                    { "sType": "html" },
                    { "sType": "html" },
                    null
                ],
        "oLanguage": {
            "sUrl": "templates/rhuk_milkyway/dataTables/media/language/it_IT.txt"
        }
    });

With this you have pagination and filtering server side
EDIT 3 - in the case you have mentioned (datatables takes care of paginetion but no calls for filtering) you  must add som extra plugin, i think. You must disable filters and sorters of datatable at inizialization fase like this;
    "bFilter": false,
    "bSort": false,

And then use another component for sorting filtering what's on screen. You can take a look here for a solution with sorting and filtering: http://silverwareconsulting.com/index.cfm/2008/10/2/jquery-autofiltering-table
(personally i don't like the idea of filtering by clicking, but you can build on this if you want to use somethin more to your taste), in any case you can't use datatables built-in filters if you allow server side pagination

A: I've got something nearly identical running, and the solution was pipelining all the way--nothing else magical and no need to combine other solutions.  Set the pipeline volume high -- in my case I'm grabbing essentially 5 "groups" of results (pages * display results) both forward and backward -- and trust that Datatables will do the rest.
In one instance of my app, I'm dealing with 5 million+ records.  Yes, it's a lot.  I've done a ton of testing on the various elements of the system, including the queries, the database optimization, indexing, and UI pattern usage.  All point to this system being the most efficient possible for the situation.  For your case, I'd strongly reccomend some performance monitoring regardless of your UI decision to see what (if any) bottlenecks exist.  In my 5 million+ record system, I'm looking at about 2-4 seconds of query time and +-5% load per page or sort, which is certainly manageable.  I've got hundreds of users and quite a few other processes to deal with as well simultaneously, and we're seeing no noticeable lag since implementing multiple DataTables about 6 months ago.
From a UI standpoint, the weakness of sorting only the on-screen data is that it's not intuitive.  When I've got access to thousands or millions of records on a grid and I sort or filter it, I expect to see the sort and filter of all the available records.  It sounds silly, but remember that the science of UI design is all about creating patterns that are "familiar" to the user.

A: Please refer below code will help you to get data from database without making datatable serverside:"true". this will be best way according to me instead of making datatable serverside and writing large sql query and applying filters separately.
$.ajax({
  type: "POST",
  url: '@Url.Action("AjaxMethodAsset", "DemoSet")',
  data: { /*parameters*/},
  dataType: "json",
  success: OnSuccess,
  failure: function(response) {
    alert(response.d);
  },
  error: function(response) {
    alert(response.d);
  }
});
function OnSuccess(response) {
  $("#tblasset").DataTable(
    {
      "destroy": true,
      'columnDefs': [
        //hide the second & fourth column
        {
          'visible': false,
          'targets': [2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 14, 15]
        },
      ],
      "order": [0, 'desc'],
      "iDisplayLength": 2,
      bLengthChange: false,
      lengthMenu: [[5, 10, -1], [5, 10, "All"]],
      bFilter: true,
      bSort: true,
      bPaginate: true,
      data: response,
      columns: [
        { 'data': 'AssetTagNo' },
        { 'data': 'ArticleNo' },
        //Other columns,
      ]
    });
  };


text:
Q: why does batch file execute different lines than what it contains i typed this line in a bat file (pause just to see what got typed)
    start my_program -m y -f %s_%d_fix -z n
    pause

it ends up running this
    start my_program -m y -f d_fix -z n

as you can see the %s_% part gets removed
i tried looking for wether the % caused reading the lines differently but it's just fine when typing in cmd
the launched program gets incorrect arguments, any thoughts on this? thanks.

A: Windows Cmd and MS-DOS Command.com use % to indicate environment variables. In your case, %s_% is interpreted as a variable expansion (with s_ acting as the variable's name), and is expanded to an empty string.
To preserve the % sign unaltered, use %%s_%%d_fix.


text:
Q: Reactjs rerender input but don't change checked status i use reactjs to make a quiz app, when I change quiz everything change but the checked status dont change(no props or state here). Change view quiz  by this code:
render: function () {
            var content = [];
            var answers = this.props.quiz.answer;
            if (this.props.quiz.type == "single") {
                for (var i = 1; i <= Object.keys(answers).length; i++) {
                    content.push(

                        <input type="radio"  value={answers[i]} />
                        {answers[i]}

)
                }
                ;
            } else if (this.props.quiz.type == "multi") {
                for (var i = 1; i <= Object.keys(answers).length; i++) {
                    content.push(

                        <input type="checkbox"  value={answers[i]} />
                        {answers[i]}

)
                }
                ;
            } else if (this.props.quiz.type == "text") {
                content.push(

                    <input type="text"/>

)
            } else {
                content.push(

)
            }

            return (
                    <form className="quiz">
                    {content}
                    </form>
            )

I make a issue for react too but they said this is only usage question,https://github.com/facebook/react/issues/4583
Anyone has this problem like me ?
Update 1:
https://jsfiddle.net/bsn6ckgv/2/
My flow: when user answered and click next question this will render another question. This is my old version have some bug ,Tomorrow I will update this . But when you check and next , the view change all but checked info didn't remove
Update 2:
https://jsfiddle.net/bsn6ckgv/29/
I think I need minimize my code as small as it can be instead of update all Logic and many unused component in it. Flow here: You check an answer and click "check Answer" -> You move to a new question . But there no change in checked status :| every thing rerender .... I didn't put any logic check answer here . Seem like need to add state or props for it put to manage the checked info.
Update 3: fixed
            if (this.props.quiz.type == "single") {
                for (var i = 1; i <= Object.keys(answers).length; i++) {
                    content.push(

                        <input type="radio"  value={answers[i]} />
                        {answers[i]}

)
                };
            } else if (this.props.quiz.type == "multi") {
                for (var i = 1; i <= Object.keys(answers).length; i++) {
                    content.push(

                        <input type="checkbox"  value={answers[i]} />
                        {answers[i]}

)
                }
                ;

A: Now I can fix this problem there. Problem here is the keys of component When keys change this checked status reset. SO I set keys with prefix is my Question index and everything now Ok :D


text:
Q: storing and retrieving ajax xml response in sessionStorage I am getting XML response from ajax and then I am trying to store it in sessionStorage but I cannot retrieve it.
$.ajax({
        url: '/webservice.svc/getProfile',
        data: { "memberId": $(authenticateResponse).find("memberId").text() },
        method: "GET",
        async: false,
        success: function (d) {
            sessionStorage.clear();
            sessionStorage.setItem('ALMS', d);
        }
    });

When I try to retrieve
console.dirxml(sessionStorage.ALMS)
[object XMLDocument]
console.dirxml($(sessionStorage.ALMS))

What I am doing wrong !!

A: The issue you have is that sessionStorage can only hold strings. Due to this the XMLDocument is being coerced using toString(), hence the value you're seeing.
To fix this you need to serialise the XMLDocument manually before saving it. Try this:
$.ajax({
  url: '/webservice.svc/getProfile',
  data: {
    memberId: $(authenticateResponse).find("memberId").text()
  },
  method: "GET",
  success: function (d) {
    sessionStorage.clear();
    sessionStorage.setItem('ALMS', new XMLSerializer().serializeToString(d));
  }
});

Also note that I removed async: false as it's incredibly bad practice.


text:
Q: Building standalone Spring Boot app with hibernate connection I'm trying to build a simple application, which connects with database and saves some data in it, let's say once per hour. I found some tutorials on pages like baeldung, but their solutions doesn't work for me.
Here is my configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

<context:component-scan base-package="io.github.steve"/>

        <!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>

        <!-- Step 5: Define Spring MVC view resolver -->

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="messages"/>
</bean>

<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
      destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/articles?useSSL=false"/>
<property name="user" value="root"/>
<property name="password" value=""/>
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="20"/>
<property name="maxIdleTime" value="30000"/>
</bean>

<bean id="sessionFactoryXXX" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan" value="io.github.steve.webscraping.domain"/>
<property name="hibernateProperties">
    <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        <prop key="hibernate.show_sql">true</prop>
    </props>
</property>
</bean>

<bean id="myTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactoryXXX"/>
</bean>

<tx:annotation-driven transaction-manager="myTransactionManager"/>

        </beans>

ArticlesDaoImpl:
@Repository
public class ArticlesDaoImpl implements ArticlesDao {
    @Autowired
    SessionFactory sessionFactory;

    @Override
    public List<Article> getAllArticles() {
        Session session = sessionFactory.getCurrentSession();
        Query<Article> query = session.createQuery("from Article order by uploadDate", Article.class);
        return query.getResultList();
    }

    @Override
    public void addArticle(Article article) {
        Session session = sessionFactory.getCurrentSession();
        session.persist(article);
    }

}

ArticlesServiceImpl:
@Service
public class ArticlesServiceImpl implements ArticlesService {
    @Autowired
    private ArticlesDao articlesDao;

    @Override
    @Transactional
    public List<Article> getAllArticles() {
        return articlesDao.getAllArticles();
    }

    @Override
    @Transactional
    public void addArticle(Article article) {
        articlesDao.addArticle(article);
    }

    @Override
    @Transactional
    public void addArticles(List<Article> articles) {
        articles.stream().forEach(articlesDao::addArticle);
    }
}

And now:
First of all, I don't know where should I put my xml config file.
I have no idea how to build my Main.class. I want to Autowire ArticlesService to Main class and run a method from it. When i use just SpringApplication.run(Main.class, args), it loads and finishing with exit code 1.
Main app:
@SpringBootApplication
@EnableScheduling
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

ScheduledTasks:
@Component
public class ScheduledTasks {
@Autowired
ArticlesService articlesService;

private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

@Scheduled(cron = "* * * * *")
public void reportCurrentTime() {
    articlesService.addArticles(new MkyongWebScraper().getArticlesList());
}

}
I'm really new in Spring and I know this question is pretty wide, but I can't find any suitable sources for my tasks. What am I doing wrong?

A: I am afraid the code you are writing, especially the XML config does not take advantage of the easier and more convenient offered with Spring Boot, and Spring Boot 2.
To generate the skeleton of your project, go to Spring Boot Initializer. You can choose the dependencies you want (in your case, it should "JPA" which is based on Spring Data JPA) and then you can download a zip with your project.
You might want to have a look at Spring Boot documentation. There are also some pretty interesting videos to "get started with Spring Boot" on youtube..
Once you have your project, you can add Spring Data JPA code...
Spring Boot documentation has a section about Spring Data JPA, but you can also find more info in the documentation of Spring Data JPA project.
Best of luck

A: I already solved my problem. I just didn't understood Spring enough. For people like me I recommend Spring in Action by Craig Walls.


text:
Q: How to store / fetch a struct with Redis in Rust? I'm trying to figure out how to

*

*programically instantiate a struct with set values (one of those might be yet another nested struct - or not) - and save it in Redis.

*fetch it back into a struct from Redis

I am aware that the 2 traits ToRedisArgs and FromRedisValue are to be implemented here, but even for my very simple 2 structs I have no clue what to write to impl them in Rust. I've made a simple example:
extern crate redis;
use redis::Commands;

// fn fetch_an_integer() -> redis::RedisResult<isize> {
//     // connect to redis
//     let client = try!(redis::Client::open("redis://127.0.0.1/"));
//     let con = try!(client.get_connection());
//     // throw away the result, just make sure it does not fail
//     let _ : () = try!(con.set("my_key", 42));
//     // read back the key and return it.  Because the return value
//     // from the function is a result for integer this will automatically
//     // convert into one.
//     con.get("my_key")
// }

fn fetch_a_struct() -> redis::RedisResult<MyStruct> {
    // connect to redis
    let client = try!(redis::Client::open("redis://127.0.0.1/"));
    let con = try!(client.get_connection());
    // throw away the result, just make sure it does not fail

    let another_struct = AnotherStruct{x: "another_struct".to_string()};
    let mut my_vec: Vec<AnotherStruct> = Vec::new();
    my_vec.push(another_struct);
    let my_struct = MyStruct{x: "my_struct".to_string(), y: 1, z: my_vec};

    let _ : () = try!(con.set("my_key_struct", my_struct));

    con.get("my_key_struct")
}

fn main() {
    match fetch_a_struct() {
        Err(err) => {
            println!("{}", err)
        },
        Ok(x) => {
            println!("{}", x.x)
        }
    }

}

struct MyStruct {
    x: String,
    y: i64,
    z: Vec<AnotherStruct>,
}

struct AnotherStruct {
    x: String
}

(Playground)
I need to save different visitors, their browsing behavior (duration, pages visited and other interactions etc) and other stats while they browse around my website - That's why I was thinking about using Redis instead of MongoDB, as my outproc session store.
In MongoDB I'd have a user collection, interactions collection etc... but what might the equivalent way in Redis be?
Being a complete newbie at both Redis and Rust I hope you can help me at least to get a few ideas how to achieve something like this.

A: Serialize your data to a JSON string, save it as a string and then deserialize it when needed.


text:
Q: Siemens logo Shadows and AWS IoT Timestream problem I´m trying to separate my shadow data values from Siemens Logo device into correct columns - each value should be written to Amazon Timestream separately however they value names contains characters like dashes etc. and I´m not able to separate the values by setting SQL filter.
The best what I was able to done was to set:
// Rule query statement
SELECT state.reported FROM '$aws/things/HneviceIoT1/shadow/update'

So I was able only select all data from the shadow file update and set
Dimension Name: device_id
Dimension Value: ${clientId()}

The result in Timestream looks unusable - attached print screen

Any help and Ideas would be very very appreciated.
Example of shadow document.
// Device Shadow state:
{
  "state": {
    "reported": {
      "AM..4:1-1": "0027",
      "I..1:1-1": "00",
      "I..1:2-1": "01",
      "Q..1:5-1": "01",
      "M..1:25-1": "01",
      "M..1:1-1": "00"
    }
  }
}

// Device Shadow metadata
{
  "metadata": {
    "reported": {
      "AM..4:1-1": {
        "timestamp": 1633104862
      },
      "I..1:1-1": {
        "timestamp": 1633104862
      },
      "I..1:2-1": {
        "timestamp": 1633104862
      },
      "Q..1:5-1": {
        "timestamp": 1633104862
      },
      "M..1:25-1": {
        "timestamp": 1633104862
      },
      "M..1:1-1": {
        "timestamp": 1633104862
      }
    }
  }
}

A: I am facing the same problem.
The best solution I found is to use an AWS Lambda function:

*

*Use an Iot rule to send your data to Lambda (set Lambda as rule destination);

*Access your data in Lambda;

*Save your data in Timestram using AWS SDK.

In Lambda I can access the Logo! telemetry values as a dictionary. I used C# (.Net6) but the same principle can be used with a programming language of your choice.
I created a message structure in C#:
public class TelemetryMsg
{
    public Dictionary<string, string>  State { get; set; } = new Dictionary<string, string>();
    ...
}

Then I can access data using C# notation:
public TestFunction (TelemetryMsg msg)
{
    string myData = msg.State["I..1:1-1"]
}

A: Another solution is this:
AWS IoT Rule re-publish topic MQTT
using Timestram as destination instead of MQTT.


text:
Q: Postfix Thinks VSFTPd is... Postfix? [root@dc ~]# service postfix status
master (pid  1616) is running...

[root@dc ~]# ps -FHww -p 1616
UID        PID  PPID  C    SZ   RSS PSR STIME TTY          TIME CMD
root      1616     1  0  1794   684   0 20:50 ?        00:00:00 /usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf

So, any theories?

A: This is likely caused by a stale pid file. The specifics will vary by distribution.


text:
Q: API (total restrictions): Lcom/android/org/conscrypt/ConscryptEngineSocket;->setUseSessionTickets(Z)V I have following Error in Google Play before app publish.
Can You help how to resolve it ? Maybe I should update some libs ?
Interface API (total restrictions): Lcom/android/org/conscrypt/ConscryptEngineSocket;->setHostname(Ljava/lang/String;)V
StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Lcom/android/org/conscrypt/ConscryptEngineSocket;->setUseSessionTickets(Z)V
    at android.os.StrictMode.lambda$static$1(StrictMode.java:416)
    at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2)
    at java.lang.Class.getDeclaredMethodInternal(Native Method)
    at java.lang.Class.getPublicMethodRecursive(Class.java:2079)
    at java.lang.Class.getMethod(Class.java:2066)
    at java.lang.Class.getMethod(Class.java:1693)
    at okhttp3.internal.platform.OptionalMethod.getPublicMethod(OptionalMethod.java:164)
    at okhttp3.internal.platform.OptionalMethod.getMethod(OptionalMethod.java:149)
    at okhttp3.internal.platform.OptionalMethod.invokeOptional(OptionalMethod.java:66)
    at okhttp3.internal.platform.OptionalMethod.invokeOptionalWithoutCheckedException(OptionalMethod.java:86)
    at okhttp3.internal.platform.AndroidPlatform.configureTlsExtensions(AndroidPlatform.java:122)
    at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:314)
    at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:283)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:168)
    at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
    at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
    at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
    at okhttp3.RealCall.execute(RealCall.java:92)
    at com.google.firebase.crashlytics.internal.network.HttpRequest.execute(HttpRequest.java:129)
    at com.google.firebase.crashlytics.internal.settings.network.DefaultSettingsSpiCall.invoke(DefaultSettingsSpiCall.java:86)
    at com.google.firebase.crashlytics.internal.settings.SettingsController$1.then(SettingsController.java:200)
    at com.google.firebase.crashlytics.internal.settings.SettingsController$1.then(SettingsController.java:193)
    at com.google.android.gms.tasks.zzo.run(com.google.android.gms:play-services-tasks@@17.1.0:2)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at com.google.firebase.crashlytics.internal.common.ExecutorUtils$1$1.onRun(ExecutorUtils.java:60)
    at com.google.firebase.crashlytics.internal.common.BackgroundPriorityRunnable.run(BackgroundPriorityRunnable.java:27)
    at java.lang.Thread.run(Thread.java:923)

A: Logcat implies that you are using a non sdk api, according to docs https://developer.android.com/guide/app-compatibility/restrictions-non-sdk-interfaces


text:
Q: How to remove listener in another screen - React Native I want to alert a user before leaving a screen (NewNews.js). It works fine, but I do not want it to be called when he click the save button (PreviewSave.js). Remove listeners are no longer maintained.
After pressing save button the customAlert is triggered. I would like to remove the listener in save function (PreviewSave.js) but it is not working.
NewNews.js
let exitListener;

useEffect(() => {
    exitListener = navigation.addListener('beforeRemove', e => {
        e.preventDefault();
        customAlert(                 // <- alerting user and waiting for his response
            string.exit,
            string.exitMore,

            () => {
                navigation.dispatch(e.data.action);
            },
            () => {
                console.log('Cancel Pressed');
            },
            string.understand,
        );

    return () => exitListener()
    },[]);

const renderScene = (...) => {
    ...
    return (
        <PreviewSave ...
            navigation={navigation}
            listener={exitListener}.        // here I try to pass the listener
        />
    );
}

return (
    ...
    <TavView ...
        renderScene={renderScene} ... />
);

PreviewSave.js
...
const save = async () => {
    // listener()
    // listener.remove();
    listener;                              // none of these work

    if (route?.item) {
        navigation.goBack();
        navigation.navigate(string.articles, {
            screen: string.article
        });
    } else {
        navigation.goBack();
    }
};

return (
    ...
    <TouchableOpacity onPress={() => save()}>
         <Text>{string.save}</Text>
    </TouchableOpacity>

);

dependencies
    "react": "^17.0.2",
    "react-native": "^0.67.4",
    "@react-navigation/bottom-tabs": "^6.0.9",
    "@react-navigation/drawer": "^6.1.8",
    "@react-navigation/native": "^6.0.6",
    "@react-navigation/stack": "^6.0.11"

A: Actually, your variable is going to be reset on the next render batch, and the function to remove the listener will be lost. To retain the function on consequent renders, you need to use useRef
let exitListener = useRef();

useEffect(() => {
    exitListener.current = navigation.addListener('beforeRemove', e => {
        e.preventDefault();
        customAlert(                 // <- alerting user and waiting for his response
            string.exit,
            string.exitMore,

            () => {
                navigation.dispatch(e.data.action);
            },
            () => {
                console.log('Cancel Pressed');
            },
            string.understand,
        );

    return exitListener;
    // return () => exitListener()
    });

And then pass it.
const renderScene = (...) => {
    ...
    return (
        <PreviewSave ...
            navigation={navigation}
            listener={exitListener.current}
        />
    );
}


text:
Q: ES2015 compilation failing when setting NODE_PATH I'm trying to get a node.js application up and running where I can:

*

*use the latest features in ES2015

*have a simpler import path (https://gist.github.com/branneman/8048520#better-local-require-paths-for-nodejs)

I've got the first part all figured out, but for some reason when I update the NODE_PATH environment variable, everything goes to crap. I've been trying to debug this for about a day and can't seem to find the right solution.
If someone can help point me in the right direction, I would totally appreciate it. Thanks!
Github repo: https://github.com/alvincrespo/failing-es2015-compilation
terminal output
➜  app git:(master) ✗ npm start

> app@1.0.0 start /path/to/app
> NODE_PATH=./src gulp

[15:20:29] Requiring external module babel-register
[15:20:29] Using gulpfile ~/workspace/app/gulpfile.babel.js
[15:20:29] Starting 'default'...
[15:20:29] Starting 'server'...
[15:20:29] Finished 'server' after 496 μs
[15:20:29] Starting 'build'...
[15:20:29] Starting 'clean'...
[15:20:29] Finished 'clean' after 5 ms
[15:20:29] Starting 'babel'...
[15:20:29] Finished 'babel' after 269 ms
[15:20:29] Starting 'copy'...
[15:20:29] Finished 'copy' after 1.67 ms
[15:20:29] Finished 'build' after 277 ms
[15:20:29] Starting 'restart'...
[15:20:29] Finished 'restart' after 8.94 ms
[15:20:29] Starting 'watch'...
livereload[tiny-lr] listening on 35729 ...
/path/to/app/src/routes.js:1
(function (exports, require, module, __filename, __dirname) { import usersController from 'controllers/users';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/path/to/app/dist/index.js:19:15)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

A: Looks like I didn't quite understand how NODE_PATH could be set to allow for "absolute" resolved paths. The update I had to make was to set the NODE_PATH to the dist directory:
package.json
  "scripts": {
    "start": "NODE_PATH=./dist gulp",
    "test": "NODE_PATH=./dist gulp test"
  },


text:
Q: why change "complex*16" to "complex(16)" cause the runtime increased unreasonably in fortran? This fortran code was originally written in Fortran 77 format(I will show it later). After I got it, I changed it into f90 free format via a converting tool. Using intel fortran compiler ifort, the compiation and running is just as fine as before.
Then I want to do more, I want to transform nonstandard,obsolete data type declaration f77 style like: real*8, complex*16 etc into f90 standard real(8), complex(16).
But I found an unbelievable thing. I just changed one "complex*16" into "complex(16)", then the running time increased from 10 seconds to 2 minutes. How could it be!!?? Can someone explain this abnormal behaviour in fortran?

Below is the details
The source file can be downloaded source code download link 1 or souce code download link 2
first, you could compile the f90 file using ifort, ignoring all the warning as
ifort -w test-16.f90

and run
./a.out

it will be finished in about 10 second (depends on your computer).
Now, we make a small change. Go to line 734, this line reads
  Complex *16 ch, clamda, czero, cspw, com, phase, ctemp

it is f77 obsolete style, so change it into f90 standard
  Complex(16) ch, clamda, czero, cspw, com, phase, ctemp

and compile in the same way, ifort will show an error
/tmp/ifortvaXMFi.o: In function `fite4_':
test-(16).f90:(.text+0x9ecf): undefined reference to `dimag_'
test-(16).f90:(.text+0xa354): undefined reference to `dimag_'

I don't know why, but I figure out that there is a very suspicious sentence in line 744
  aimag(ctemp) = dimag(ctemp)

I really don't understand what does mean. But the whole code only has three places that "ctemp" appear. So apparently, this line is rebundant. So we can safely delete it.
So after deleting line 744, the compilation is OK. But the running time as I said before increased to more than 2 minutes. It is really unbelievable, what is wrong here?

A: Oh dear. A kind value is not the same number as the bytes that a variable occupies. In most (but not all) compilers complex(16) is quadruple precision (where supported), and that is why your run time goes through the roof. Please learn about kind values, see for instance
Fortran 90 kind parameter
to get started, and then understand that for complex variables the kind values are the same as the kinds of the real values that constitute it.
I'm not going to say more as, to be honest, if somebody posts a relatively long program and then tells me to ignore the warnings during compilation and then sort out their problem, well I don't feel that inclined to put much effort in. Fix the warnings, cut the program down to at most a few tens of lines, and then I, and I suspect most other people, will look more carefully.


text:
Q: Matlab Deciding Output based on matrix condition So I have this matrix
A=
7

B=
0.34   0.34   0.34
0.50   0.25   0.25

and this matrix
C=
1
1
4
2
3
6
3

with this rule:

*

*if C=1 then the output = sum(A*(B first row) )

*if C=2 then the output = sum(A*(B 2nd row) )

*if C is not 1 or 2 then output = C value

or in general:

*

*if the C-th row exist in B then the output = sum(A*(C-th row of B) )

*otherwise output = C value

So the output should be like this:
output=
7.14
7.14
4
7
3
6
3

I'm trying using this code but its doesn't work
sizeA=size(A,1)
sizeB=size(B,1)
for i=1:sizeB
    if (B(i)<=sizeA)
        Output=sum(repmat(A,1,length(C))'.*B(C,:),2)
    else
        Output=C(i)
    end
end

A: The correct code is:
sizeA=size(A,1);
sizeB=size(B,1);
sizeC=size(C,1);
Output = zeros(size(C)); % preallocate memory for efficiency
for i=1:sizeC
    if C(i)<=sizeB
        Output(i)=sum(A * B(C(i), :));
    else
        Output(i)=C(i);
    end
end

You can also avoid a for loop in the following way:
% make B of the same size as C
B_ = zeros(size(C));
B_(1:size(B, 1)) = sum(B, 2);
% calculate the output
output = C .* (C > size(B, 1)) + A .* B_(C)

Please try to understand the code and not to just use it.

A: I simplified a little bit. It works.
for i=1:length(C)
num=C(i);
switch num
case 1
output(i)=sum(A*B(1,:))
case 2
output(i)=sum(A*B(2,:))
otherwise
output(i)=C(i);
end
end

output =

  Columns 1 through 5

    7.1400    7.1400    4.0000    7.0000    3.0000

  Columns 6 through 7

    6.0000    3.0000


text:
Q: Scheduler for Web application ASP.NET MVC I've built a website application by ASP.NET MVC that helps user get RSS news. Of course, it works perfectly. However, I want to expand the function that the website will automatic send hot news to user's email at 6.00 am daily, for example.
I've found solutions on internet but I still confused among using Quartz.NET, Windows Service, and Schedule in windows.
Please tell me where I should begin !
Thanks so much !

A: First of all you will need to create a windows service: http://msdn.microsoft.com/en-us/library/zt39148a.aspx
Quartz.NET has a useful tutorial here: http://quartznet.sourceforge.net/tutorial/lesson_1.html
What I would do would be to initialize your scheduler in the OnStart() override and eventually stop it in the OnStop().
Basically you can define triggers using the Trigger class and Jobs by creating an implementation of the IJob interface, then use the scheduler to attach triggers to jobs. Everytime a trigger fires, the Execute method of the Job is run.
Putting the entire explanation here would be way too long, but following the tutorials should get you where you want to be in matter of minutes. Good luck!
Of the other end, there is a much simpler solution than writing a windows service. Just write a console app and then, through the Task Scheduler interface (Control Panel -> Administrative Tools in Win 7), create a task that runs your app at the time you want. For a simple task that needs to run once a day this is probably a better solution rather than keeping a service up 24/7.


text:
Q: Copying AD group members to another AD group I need to copy all members from one AD group to another.  The code I am using is failing.
Caveat: The members in the source group are from different (trusted) domains.
I am not a Powershell expert.
Example code:
$Source_Group = Get-ADGroupMember -Identity "CN=Team1_ReadOnly,
OU=Team1,OU=TEAM_GROUPS,OU=Groups,OU=Business,DC=Server1,DC=Contoso,DC=com"
-Server "Server1@contoso.com"
Add-ADGroupMember -Identity " CN=Team2_ReadOnly,
OU=Team2,OU=TEAM_GROUPS,OU=Groups,OU=Business,DC=Server1,DC=Contoso,DC=com "
-server "Server1@contoso.com" -Members $Source_Group

Error Output:

Has anyone come across this issue before with users from different domains?
We have moved all users who are in the same domain as the destination group without issue in the past.

A: To answer my own question.
The code was fine.  It turns out the person (DBA) running the script was running it directly from the target domain controller.  The target domain controller did NOT have a trust with a particular domain that one of the members was attributed to.  I tested from my local machine that had rights across all domains.
When the script was run on a machine that had a trust with all domains it worked fine.


text:
Q: MvcSiteMapProvider and Autofac issue with InstancePerRequest I've installed nutget package MvcSiteMapProvider.MVC5.DI.Autofac.Modules.
I'm trying to register my DBContext as InstancePerRequest. This however fails with the error
No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested.

If I change my DBContext to InstancePerLifetimeScope, all is well. The error is thrown in the file
DI\Autofac\Modules\MvcSiteMapProviderModule.cs    Line: 195

Actually, if I try to register any of my own types with InstancePerRequest, I get this error. I'm new to Autofac so don't really understand a lot of the code in the nuget package forMvcSiteMapProvider Autofac. While I'm learning more about Autofac, hoping someone can point in the right direction as to how to get around this issue?
EDIT:
From Autofac docs, I'm getting the error because:
Code is running during application startup (e.g., in an ASP.NET Global.asax) that uses dependency resolution when there isn't an active request yet.

According to MvcSiteMapProvider docs, this line is required though, so can I move this somewhere else?
// Setup global sitemap loader (required)
MvcSiteMapProvider.SiteMaps.Loader = container.Resolve<ISiteMapLoader>();

EDIT 2:
protected void Application_Start()
{
    // BEGIN: Autofac Config
    var builder = new ContainerBuilder();

    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    builder.RegisterControllers(typeof(MvcApplication).Assembly);
    builder.RegisterSource(new ViewRegistrationSource());

    // Register context and unit of work here
    IoC.Dependencies.Register.RegisterTypes(builder);

    builder.RegisterModule(new MvcSiteMapProviderModule());
    builder.RegisterModule(new MvcModule());

    var container = builder.Build();

    MvcSiteMapProvider.SiteMaps.Loader = container.Resolve<ISiteMapLoader>();

    GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    // END: Autofac Config

    Helpers.Log4NetManager.InitializeLog4Net();
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}

A: You are registering your controllers twice with Autofac.
// This registers the all of the controllers in the application
builder.RegisterControllers(typeof(MvcApplication).Assembly);

// And so does this...
builder.RegisterModule(new MvcModule());

Contents of MvcModule:
public class MvcModule
    : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var currentAssembly = typeof(MvcModule).Assembly;

        builder.RegisterAssemblyTypes(currentAssembly)
            .Where(t => typeof(IController).IsAssignableFrom(t))
            .AsImplementedInterfaces()
            .AsSelf()
            .InstancePerDependency();
    }
}

UPDATE
From here:

The error pretty much says it all - something in your registrations has a dependency that is registered as InstancePerRequest and it's being resolved outside of a web request.

I am not sure that registering DBContext as InstancePerRequest is such a good idea. MvcSiteMapProvider loads before any request context is created, so if you are using dynamic node providers or custom ISiteMapNodeProvider implementations that access the database, it isn't going to work. A better choice would be to use InstancePerDependency which is not dependent upon HttpContext.
Instance Per Dependency
Also called 'transient' or 'factory' in other containers. Using per-dependency scope, a unique instance will be returned from each request for a service.


text:
Q: SQL Expression missing error I am trying to select from a table with the average of columns from other tables from other tables; The schema is as follows.
Students (sid, firstname, lastname, status, gpa, email)
Enrollments (sid, classid, lgrade)
Grades (lgrade, ngrade)
And the erroneous query is,
select sid, lastname,
avg( select g.ngrade from grades g, enrollments e
    where e.sid = sid and g.lgrade = e.lgrade and e.lgrade is not null
    and g.ngrade is not null) as cgpa
from students
order by cgpa asc;

A: Take the semi-colon out of your subquery.

A: There are several issues:

*

*Remove the semicolon from the subquery.

*You're attempting to use a correlated subquery as a value expression. That's fine, but you have to wrap it in parentheses to do so. I only see one set of parentheses, the ones for the avg() function.

*You're also missing an alias on a column. For clarity in expressing your intent, you should be consistent and use aliases throughout.

*Last, a GROUP BY clause is required somewhere.

All in all, I think the aggregate should be inside the parentheses.
Try:
select
   sid,
   lastname,
   (
      select avg(g.ngrade)
      from grades g, enrollments e
      where e.sid = sid and g.lgrade = e.lgrade
      and g.ngrade is not null
   ) as cgpa
from students
order by cgpa asc;

Other notes: e.lgrade is not null is not needed since the condition g.lgrade = e.lgrade already ensures it won't be null.
Last, I encourage you to learn ANSI join syntax. You'll thank me later. Seriously, using old-style joins is awful.
select
   s.sid,
   s.lastname,
   (
      select avg(g.ngrade)
      from
         grades g
         inner join enrollments e
            on g.lgrade = e.lgrade
      where
         g.ngrade is not null
         and s.sid = g.sid
   ) as cgpa
from students s
order by cgpa asc;

In fact, I have a suspicion that simply rewriting the query this way will help expose what's wrong with it--it looks to me like maybe the grades and enrollments tables need another join condition?

A: Two INNER JOINs without sub-queries - please try.
SELECT s.sid, s.lastname, avg(g.ngrade) cgpa
FROM Students s
JOIN Enrollments e ON s.sid = e.sid
JOIN Grades g ON e.lgrade=g.lgrade
GROUP BY s.sid, s.lastname
ORDER BY 3;


text:
Q: fixed height div with overflow causes wrapping of content I have a list of bullets inside a div with a fixed height. Width is dynamic, determined by the content of the div, which in this case is a bullet list.  The overflow is set to auto, so when a longer list is used, it adds a scrollbar to the div.
The issue is that when it adds the scrollbar, the list items no longer fit the same, and it causes the longer one(s) to wrap, where they would normally sit hard into the right margin.
Example fiddle here: http://jsfiddle.net/6uguL/
#wrap {
  height: 150px;
  border: 1px solid #ff0000;
  overflow: auto;
  display: inline-block;
}

short list item 1

short list item 2

short list item 3

this list item longer

short list item

short list item

short list item

If you change the height of the div to 250px the list sits nicely, one per line, no wrapping, but set the height to 150px and the long line now wraps because of the scrollbar being added.
Is there a way to account for the potential existence of the scrollbar and add padding/margin/whatever to stop any unnecessary wrapping occurring?
Note that white-space:nowrap is not an option and the div should only be as wide as it needs, based on the content, but still allow wrapping for very long lines if needed (in case some lines are very, very long)

A: I have some possibilities, but they all have a downside, so I guess some people will find better answers :

*

*You can ad overflow-y:scroll; to the division. The scroll-bar will always be here, but just greyed out

*Ad some padding-right to compensate the room taken by the scroll-bar

*I think this one is the best solution : Download perfect-scrollbar. It is a jQuery plugin that do not affect the original design layout. If you can use JavaScript and jQuery, that's the best solution I have


text:
Q: How does Python 2 represent Unicode internally? When I read this Python2's official page on Unicode, it says

Under the hood, Python represents Unicode strings as either 16-or 32-bit integers, depending on how the Python interpreter was compiled.

What does above sentence mean? Could it mean that Python2 has its own special encodings of Unicode? If so, why not just use UTF-8?

A: This statement simply means that there is underlying C code that uses both these encodings and that depending on the circumstances, either variant is chosen. Those circumstances are typically user choice, compiler and operating system.
Now, for the possible rationale for that, there are reasons not to use UTF-8:

*

*First and foremost, indexing into a UTF-8 string is O(n) in complexity, while it is O(1) for UTF-32/UCS4. While that is irrelevant for streamed data and UTF-8 can actually save space for transmission or storage, in-memory handling is more convenient with one character per Unicode codepoint.

*Secondly, using one character per codepoint translates very well to the API that Python itself provides in its language, so this is a natural choice.

*On MS Windows platforms, the native encoding for UI and filesystem is UTF-16, so using that encoding provides seamless integration with that platform.

*On some compilers wchar_t is actually a 16-bit type, so if you wanted to use a 32-bit type there you would have to reimplement all kinds of functions for your self-invented character type. Dropping support for anything above the Unicode BMP or leaking surrogate sequences into the Python API is a reasonable compromise then (but one that sticks unfortunately).

Note that those are possible reasons, I don't claim that these apply to Python's implementation.


text:
Q: rsync not copying any files I'm running something like the following: rsync -av -e "ssh" --include="dir1/***" --include="file1.txt" --exclude="*" superuser@remote-server:/var/www/ /var/, and all I'm getting is the following message:
receiving incremental file list

sent 276 bytes  received 10 bytes  21.19 bytes/sec
total size is 0  speedup is 0.00

And no files are transferring over.

A: You are including subdirectories of dir1, but dir1 itself is excluded.  So none of its children are seen.
From the rsync man page:

The concept [of] path exclusion is particularly important when using a
  trailing '*' rule. For instance, this won't work:
+ /some/path/this-file-will-not-be-found
+ /file-is-included
- *

This fails because the parent directory "some" is excluded by the '*' rule, so rsync never visits any of the files in the "some" or
  "some/path" directories. One solution is to ask for all directories in
  the hierarchy to be included by using a single rule: "+ */" (put it
  somewhere before the "- *" rule), and perhaps use the
  --prune-empty-dirs option. Another solution is to add specific include rules for all the parent dirs that need to be visited. For instance,
  this set of rules works fine:
+ /some/
+ /some/path/
+ /some/path/this-file-is-found
+ /file-also-included
- *


text:
Q: ActiveRecord, NHibernate and PostgreSQL I'm kinda stuck here and can't get this to work. It seems so simple, but I must be doing something incredibly wrong.
I have a simple class to test NHibernate Active Record and PostgreSQL, take a look
[ActiveRecord]
public class Accident:ActiveRecordBase<Accident>
{
    [PrimaryKey(PrimaryKeyType.Sequence)]
    public int Id { get; set; }

    [Property]
    public string Address { get; set; }

    [Property]
    public int AddressNumber { get; set; }

    [Property]
    public testAccidentType AccidentType { get; set; }
}

public enum testAccidentType
{
    FRONT,
    BACK,
    SIDE
}

And I'm trying to create the schema from my class, like this:
public class Startup
{
    public static void StartActiveRecord()
    {
        XmlConfigurationSource source = new XmlConfigurationSource(@"c:\users\h\documents\visual studio 2010\Projects\TestNHibernate\TestNHibernate\Model\config.xml");
        ActiveRecordStarter.Initialize(source, GetActiveRecordTypes());

        ActiveRecordStarter.CreateSchema();
    }

    public static Type[] GetActiveRecordTypes()
    {
        List<Type> types = new List<Type>()
        {
            typeof(Accident)
        };
        return types.ToArray();
    }
}

ActiveRecord is able to initialize this class, but it's always stuck in CreateSchema method. Here is the config file. Any tips from the experts?
<?xml version="1.0" encoding="utf-8" ?>

<activerecord isWeb="false">
  <config>
    <add key="connection.driver_class" value="NHibernate.Driver.NpgsqlDriver" />
    <add key="connection.connection_string" value="Server=localhost;initial catalog=nhiber;User ID=postgres;Password=***;" />
    <add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
    <add key="dialect" value="NHibernate.Dialect.PostgreSQLDialect" />
  </config>
</activerecord>

EDIT: I figured this one out. the problem is that the documentation is wrong. PostgreSQL does not use the keyword "initial catalog" but it uses "database", like this:
    <add key="connection.connection_string" value="Server=localhost;database=nhiber;User ID=postgres;Password=***;" />

Thanks!

A: You need to change the connection string:
<add key="connection.connection_string" value="Server=localhost;database=nhiber;User ID=postgres;Password=***;" />