text:
Q: RDLC with .NET Core 5.0 throws error in production if I use expressions inside report creation, works fine in development I'm using RDLC to create reports with my .NET Core Web API. I spent an entire week creating 3 reports using lots of expressions. Now after publishing the application on IIS every report fails with error

An error occurred during local report processing.;An unexpected error
occurred in Report Processing.Object reference not set to an instance
of an object

The report works fine in development. After lots of research I found the issue is with expressions. I have been struggling to find a solution for almost a day searching the entire web. Many people suggested that this is the limitation of RDLC and we can't use expressions. Without expressions there is no use of this tool for me. I can't afford to spend another week to re-create those reports using another tool. In fact I don't even know what else can I use instead of RDLC to create reports.
Any suggestion to fix these issues or an alternative to RDLC will be life saving for me....
It's been a pain to use this unstable tool, but unfortunately I'm stuck in this.
Thanks

A: Having .NET Core work with library from .NET framework is painful to say the least.
Thanks for the recompiled WinForms library provided by lkosson.
I managed to make this work but it looks like bandage fix more then anything.
Very Important Note!! This solution make use of WPF, WinForms version of RDLC. This limit the .NET 5 solution to Windows build only. (I can't make Web version to work, maybe someone else can)

1. Update .NET 5 project settings
Unload the .NET 5 project
Right click and Edit .csproj

Update/Add 3 lines in property group as following:
  <PropertyGroup>
    --><TargetFramework>net5.0-windows</TargetFramework>
    <RootNamespace>Net_Core_5._0</RootNamespace>
    --><UseWindowsForms>true</UseWindowsForms>
    --><EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>
  </PropertyGroup>

Reload the project

2. Add NuGet Packages

Add and install the following packages:
Microsoft.ReportViewer.Common
Microsoft.ReportViewer.WinForms
ReportViewerCore.WinForms

3. Use .NET version's function to generate Report
This is an example for your reference,
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.Data;

namespace NET_4._8_RDLC_Lib
{
    public class ReportGenerator
    {
        /// <summary>
        /// .NET Core use this function to render reports
        /// </summary>
        public static byte[] RenderReport(String reportPath, Dictionary<string, DataTable> data, string format)
        {

            Microsoft.Reporting.WinForms.ReportViewer v1 = new Microsoft.Reporting.WinForms.ReportViewer();
            v1.LocalReport.DataSources.Clear();

            //Add all datasource to the Report
            foreach (KeyValuePair<string, DataTable> pair in data)
            {
                Microsoft.Reporting.WinForms.ReportDataSource ds = new ReportDataSource(pair.Key, pair.Value);

                v1.LocalReport.DataSources.Add(ds);

            }

            v1.LocalReport.EnableExternalImages = true;
            v1.LocalReport.ReportPath = reportPath;

            return v1.LocalReport.Render(format: format, deviceInfo: "");
        }
    }
}

The file is just inside the bytes array.


text:
Q: How to put random lines from a file into a string in python? what i want to do is write a code that has a file (in the code, no need to be input by user), and the code picks a random line from the file - whatever it is, a long line, an ip or even a word and at the end of the loop puts it into a string so i could use that in other parts of the code.
i tried using randomchoice(lines) but wasn't sure how to continue from here.
after that i tried using:
import random
def random_line(afile):
    line = next(afile)
    for num, aline in enumerate(afile):
      if random.randrange(num + 2): continue
      line = aline
    return line

which also for some reason didnt work for me.

A: The last method you posted worked for me. Maybe you are not opening the file correctly. Here is another approach, using random.choice
import random

def random_line(f):
    return random.choice([line for line in f])

f = open("sample.txt", 'r')

print random_line(f)

Edit:
Another way would be (thanks to @zhangxaochen):
def random_line(f):
    return random.choice(f.readlines())

A: Translating another answer of mine from C:
def random_line(afile):
    count = 0
    kept_line = None
    for line in afile:
        if random.randint(0, count) == 0:
            kept_line = line
        count += 1
    return kept_line

Edit: This appears to do the same thing as random.choice. I wonder if they use the same algorithm?
Edit 2: from the comments and a little experimentation it appears random.choice uses a different algorithm, which will be much more efficient if all of the elements are already in memory. This isn't usually the case for files unless you use readlines. There will be a tradeoff between having to keep the entire file in memory vs. having to calculate n random numbers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Question of Excel formula if nested error I would like to make a formula on excel file which require to meet the following requirements:

*

*If N column is empty, then nothing to do

*If N column are not C and O, then show message of "invalid value"
(Remark: A,B,D,E.....M,N,P,Q....Z)

*If N column is C and T column is empty, then show message of "please write something here"

After run, it prompt up the error message of "You've entered too many arguments for this function". May I know what's wrong with me?
Thanks.
=IF(ISBLANK(N815),"", IF(OR(N815="C",N815="O"),"","Invalid Value!", IF(AND(N815="C",ISBLANK(T815)),"Please write something here!")))

A: Did you know that you can indent your formula in the formula bar? :)
=IF(
    Something is True,
    then do something,
    otherwise do something else
   )

It is much easier to write when you want multiple IFS
=IF(
   ISBLANK(N815),
   "",
   IF(
     OR(N815="C",N815="O"),
     IF(
       AND(N815="C", ISBLANK(T815)),
       "Please write something here!",
       ""
       ),
     "invalid value"
     )
    )


text:
Q: What does the bars above the health bar mean? After drinking an energy drink, there are little yellow and white bars above the health bar. What are those? What do they represent?

A: The bars over top of your health bar shows the current boost level from using consumables. Each bar corresponds to a different level of boost:

*

*Level 1:+1% Health Regen per 8 Seconds

*Level 2:+2% Health Regen per 8 Seconds

*Level 3:+3% Health Regen per 8 Seconds and +2.5% Movement Speed Bonus

*Level 4:+4% Health Regen per 8 Seconds and +6.2% Movement Speed Bonus

You can increase the your boost level by using the following consumables
(see image below for more detail):

*

*Energy Drinks: 1.5 bars of boost (40% of total boost)

*Pain killer: 2 bars of boost (60% of total boost)

*Adrenaline Shot: 4 bars of boost (100% of total boost)

One thing to keep in mind is that the effects of using the consumables is cumulative, so drinking two energy drinks will get you to around 80% of your boost bar (slightly less, as the bar degrades while you drink the second energy drink).

Boost amount source

A: They are boosts. They come from both energy drinks and painkillers.
First 2 bars (the leftmost) are slight health improvements, meaning they can slowly heal you until the bar decays. You get faster health regeneration in the second bar.  The third bar is a speed boost, meaning you run and move slightly faster. The fourth is even more speed increase and health regeneration.
Good luck! Get those chicken dinners!


text:
Q: Unable to convert varchar2 to Date in oracle I am trying to convert one of the varchar2 column to date in oracle using      the below query.
SELECT *
FROM login
WHERE to_date(END_DATE,'DD-MM-YY') < to_date(TRUNC(SYSDATE)-90,'DD-MM-YY');

I am converting the both side to date with a common formatter. But  still I am getting the below error while executing this query.
 ORA-01861: literal does not match format string
  01861. 00000 -  "literal does not match format string"
 *Cause:    Literals in the input must be the same length as literals in
       the format string (with the exception of leading whitespace).  If the
       "FX" modifier has been toggled on, the literal must match exactly,
       with no extra whitespace.
 *Action:   Correct the format string to match the literal

Can you please help me to sort out this problem?

A:
to_date(END_DATE,'DD-MM-YY')

*

*First of all, it is a bad design to store DATE as STRING. Date should always be stored as DATE data type, there is no reason to store it as characters.

*If your data is stored as 14-Mar-2015 then why are you using the 'DD-MM-YY' format. Clearly the formats doesn't match. You should use proper format model.
For example,
TO_DATE(14-Mar-2015,'DD-Mon-YYYY','NLS_DATE_LANGUAGE=ENGLISH')

to_date(TRUNC(SYSDATE)-90,'DD-MM-YY')

*

*This makes no sense. TRUNC on DATE would return you DATE after truncating the time portion.

*Never ever use TO_DATE on DATE. It will implicitly convert it into string and then back to date using locale-specific NLS format. See a detailed explanation in my previous answer here https://stackoverflow.com/a/29559609/3989608
Your modified query would look like:
SELECT *
FROM login
WHERE to_date(END_DATE,'DD-Mon-YYYY','NLS_DATE_LANGUAGE=ENGLISH') < TRUNC(SYSDATE)-90;


text:
Q: renaming pandas df dynamically My df looks like below :-

I have to rename the columns and extract the numbers which I am doing with the below code:-
df.rename(columns={
                    0: 'latency_msecs.xmpp_login', 1: 'latency_msecs.total', 2: 'latency_msecs.message_send',
                    3: 'latency_msecs.admin_login', 4: 'latency_msecs.join_echo_channel',
                    5: 'latency_msecs.message_query',},
                    inplace=True)

df['latency_msecs.xmpp_login'] = df['latency_msecs.xmpp_login'].str.extract(r'(\d+.\d+)').astype('float')
df['latency_msecs.total'] = df['latency_msecs.total'].str.extract(r'(\d+.\d+)').astype('float')
df['latency_msecs.message_send'] = df['latency_msecs.message_send'].str.extract(r'(\d+.\d+)').astype('float')
df['latency_msecs.admin_login'] = df['latency_msecs.admin_login'].str.extract(r'(\d+.\d+)').astype('float')
df['latency_msecs.join_echo_channel'] = df['latency_msecs.join_echo_channel'].str.extract(r'(\d+.\d+)').astype('float')
df['latency_msecs.message_query'] = df['latency_msecs.message_query'].str.extract(r'(\d+.\d+)').astype('float')

Its giving me a clean df :-

How I can make the renaming and the extraction dynamic so that if my column value is "latency_msecs.message_query": 68858.58869552612, I can make the column name latency_msecs.message_query and the value will be 68858.58869552612 doesn't matter if there are 5 rows or 500.
I want to ditch the manual renaming and extraction.

A: You need to convert json to pandas dataframe. Check the code below:
import json
import pandas as pd

sample_row = '{"latency_msecs.total": 71815.09041786194, "latency_msecs.message_query": 68858.58869552612, "latency_msecs.join_echo_channel": 10.111570358276367, "latency_msecs.message_send": 9.004592895507812, "latency_msecs.xmpp_login": 1941.108226776123, "latency_msecs.admin_login": 17.666339874267578}'

df = pd.json_normalize(json.loads(sample_row))
print(df)


text:
Q: Reading input and moving files with similar names I am trying to create a script which reads the first line of a file and then moves all of files with a similar naming convention up a level.
These are 3 example files:
C:\Users\USERNAME\location\PYYYYYYYYY.txt.asc
C:\Users\USERNAME\location\holdingarea\PYYYYYYYYY.tt.asc
C:\Users\USERNAME\location\holdingarea\PYYYYYYYYY.t.asc

The script I have so far is:
$location = Read-Host -Prompt "Location Filename"
$locationfilename = Select-String C:\Users\USERNAME\location\holdingarea\*.txt.asc –pattern $location  -Context 1
$locationfilenames = $locationfilename.basename
$locationarea = "C:\Users\USERNAME\location\holdingarea"
$locationlocation = "C:\Users\USERNAME\location"

Select-String C:\Users\USERNAME\location\holdingarea\*.txt.asc -Pattern $location -Context 1 |
  Out-File -Append C:\Users\USERNAME\location\logs.txt
Move-Item -Path "$locationfilenames" -Destination "$locationlocation"

A: Your issue is arising here:
$locationfilename = Select-String C:\Users\USERNAME\location\holdingarea\*.txt.asc –pattern $location  -Context 1

Assuming you're just trying to get the filename, this should work:
$lcoationfilename = $location | Split-Path -Leaf

If it's the parent folder you're after, then this is appropriate:
$lcoationfilename = $location | Split-Path -Parent

If for some reason you're on a version of PS that doesn't have Split-Path, let me know and I'll edit to a more appropriate solution.


text:
Q: How can I start using twill? I am sorry I have already asked this question on "Superuser", but nobody answers there, so I deleted it from "Superuser" and decided to post it here. Hope it's not a big crime, especially given the fact that I was firstly advised to use twill here on "StackOverflow" (not on "SuperUser")
How do I start using twill? I have just downloaded it, unpacked it and clicked on the setup .py file in the folder. The black window (terminal) appeared for a moment and vanished.
(I do have Python 2.5 installed on my computer - along with SDK from Google App Engine)
In the twill documentation section it says:

Downloading twill
The latest release of twill is twill
  0.9, released Thursday, December 27th, 2007; it is available for download at
  http://darcs.idyll.org/~t/projects/twill-0.9.tar.gz.
  You can also use Python's easy_install
  to install or upgrade twill.
twill works with Python 2.3 or later.
To start using twill, install it and
  then type twill-sh. At the prompt
  type:
go http://www.slashdot.org/
show
showforms
showhistory

I am not clear from this passage what I am supposed to type (only "twill-sh" or "twill-sh" and all the words under that line) and where (I tried typing it in the command prompt window of my computer - to no avail)
Can, anyone, please, help me out here?
Thank You in advance.

Update 1:
(This update is a response to the answer given by S.Mark)
Hello, S.Mark!!!!
I've tried to follow Your instructions. Here is what happened:
Firstly, I created a folder on my D disk and named it "tmp". Then I downloaded and extracted twill-0.9 into that folder. So, now the path to this file on my computer was just as same as the one in Your example:  D:\tmp\twill-0.9 :

(source: narod.ru)

(source: narod.ru)
Then, I tried to open the command prompt on my computer:

(source: narod.ru)

(source: narod.ru)

(source: narod.ru)

(source: narod.ru)

(source: narod.ru)
Then, following step 2 of Your instructions, I tried to switch to D disk:

(source: narod.ru)
But for some reason it didn't work:

(source: narod.ru)
This Chinese line says something like "This action has been rejected." Why is it so?
Well, I tried to proceed to step 3 anyway, and here is what I've got:

(source: narod.ru)
As far as I can understand, this Chinese line says something like " 'C:\' is neither internal nor external command, thus, it cannot be carried out. "
Why is it so? Is there something wrong with my computer?

Update 2:
(This update is my second response to the answer given by S.Mark)
Hello, S.Mark!!! Thank You for Your answer again.
Yes, this time it worked when I just typed those parts that You highlighted in Your post. So, when I typed just "d:" in the very beginning, it worked!!!
But then, when I typed "python setup.py build", I got the same error message (" 'python'is neither an internal or external command; it can't be carried out. ") :

(source: narod.ru)
I tried to repeat this command and accidentally omitted the word "python":

(source: narod.ru)
When I pressed "Enter" key, the build process seemed to launch - at least what I saw then resembled the step 4 of Your instructions ("start the build process") very much:

(source: narod.ru)

(source: narod.ru)

(source: narod.ru)
But now I am a little bit hesitant about proceeding to step 5 ("Install It") as I am not sure if what I have done is the right thing.
If what I did in step 4 was okay, should I also omit the word "python" in step 5?
A side question: How did You manage to put the contents of the terminal into Your post without making screenshots? Is it like there is some way of putting the terminal's contents into the clipboard? Making screenshots all the time and hosting them prior to posting is quite cumbersome.

Update 3:
(This update is my third response to S.Mark)
S.Mark, hello again!!!
(Hope you are not sick and tired of me yet)
"…and yeah you could omit python and directly run setup.py because your python installation registered *.py in registry… regarding step 5, you could just run setup.py install" – I followed these words of Yours and install process ran successfully! Thank You.
But as for the following steps ("then open python prompt from start menu, and test step 6 and 8"), there wasn't much success in the Python prompt:

(source: narod.ru)
Neither was it successful in the usual command prompt (terminal):

(source: narod.ru)
(It again says in Chinese that python "is neither an internal nor external command and, therefore, can't be carried out"). Do You have any idea why it didn't work?
"…where is your python installation? C:\Python25?"
- Yes, that's right.
"…there is a setting (command prompt properties - easy edit mode) to enable selection of text on the command prompt, could you ask that in superuser.com?"
- Sure, I will ask this question there. Thanks for telling me.

A: You cannot just double click setup.py
You need to open command prompt or shell and go to that folder
and need to do
python setup.py build
python setup.py install

install step should automatically do build normally, so only last one will work

Edit: ok, here is superuser way of installation steps

*

*I have extracted twill-0.9.tar.gz to D:\tmp\twill-0.9

*I am on drive C, so I switched to D:
C:\>d:

*Now, change the folder by using cd command
C:\>cd D:\tmp\twill-0.9

*start the build process
D:\tmp\twill-0.9>python setup.py build
(WARNING: importing distutils, not setuptools!)
D:\data\program\Python26\lib\distutils\dist.py:266: UserWarning: Unknown distribution option: 'entry_points'
  warnings.warn(msg)
D:\data\program\Python26\lib\distutils\dist.py:266: UserWarning: Unknown distribution option: 'test_suite'
  warnings.warn(msg)
running build
running build_py
creating build
creating build\lib
creating build\lib\twill
......
running build_scripts
creating build\scripts-2.6
copying and adjusting twill-fork -> build\scripts-2.6

*Install it
D:\tmp\twill-0.9>python setup.py install
(WARNING: importing distutils, not setuptools!)
running install
running build
running build_py
......
running install_scripts
copying build\scripts-2.6\twill-fork -> D:\data\program\Python26\Scripts
running install_egg_info
Writing D:\data\program\Python26\Lib\site-packages\twill-0.9-py2.6.egg-info

*Test for import is or not
D:\tmp\twill-0.9>python
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import twill
  import re, base64, urlparse, posixpath, md5, sha, sys, copy
twill\other_packages\_mechanize_dist\_auth.py:14: DeprecationWarning: the sha module is deprecated; use the hashlib module instead
  import re, base64, urlparse, posixpath, md5, sha, sys, copy
>>>

*Import was fine, but there is DeprecationWarnings on python 2.6, but this should be ok and should be no warnings at all with python 2.5

*confirm its properly imported or not, you will see twill and its functions there, so yes.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'twill']
>>> from twill.commands import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'add_auth', 'add_extra_header', 'agent', 'back', 'clear_cookies', 'clear_extra_headers', 'code', 'config', 'debug', 'echo', 'exit', 'extend_with', 'fa', 'find', 'follow
>>>


text:
Q: Explicit formula to compute the conductor of Etale cohomology? I think I am stuck at a calculation problem. Suppose there is an elliptic surface $X$ defined over $Q$, take $\overline{X}:=X\times_Q \overline{Q}$, and denote by $\varphi: G_{Q}\to Aut(H^2_{et}(\overline{X}, Q_{\ell}(1)))$ the natural representation. How do I know the Artin conductor of this representation once I am given the concrete elliptic fibration? For example, suppose $X$ is defined by the affine model
$$
y^2=x(x^2+2x+t^4)
$$
With $t$ a parameter. Then is there any way to tell the conductor of the representation space $H^2_{et}(\overline{X}, Q_{\ell}(1))$?
Thanks very much.


text:
Q: Combine queries on the same table in LiteDB I am using LiteDB, and trying to improve performance. I currently have two queries on the same table, and was wondering if there is another way to combine these two queries as one to improve performance.
            using (var db = new LiteDatabase(_databaseFileName))
            {
                // Get a collection (or create, if doesn't exist)
                var collection = db.GetCollection<IdentityKeyPair>(_tableName);

                collection.EnsureIndex(x => x.Value);
                collection.EnsureIndex(x => x.RecordId);

                var entityKeyRecordId = collection.Query().Where(p => p.Value == uniqueValue).Select(x => x.RecordId).FirstOrDefault();

                if (entityKeyRecordId != Guid.Empty)
                    results = collection.Query().Where(p => p.RecordId == entityKeyRecordId).ToList();

            }


text:
Q: Pass parameter to Django REST framework serializer to use with model I have a class Object with a method state that takes a datetime parameter dt. How do I pass the datetime parameter from the URL to Object.state()?
The model:
class Object(models.Model):
    def state(self, dt=datetime.datetime.now()) -> dict:
        ...stuff...
        return {'dt': dt, 'other_stuff': stuff}

The view:
class ObjectDetail(generics.RetrieveAPIView):
    queryset = models.Object.objects.all()
    serializer_class = serializers.ObjectSerializer

    def get_serializer_context(self):
        return {'dt': self.request.query_params.get('dt', datetime.datetime.now())}

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

And the serializer classes:
class ObjectSerializer(serializers.HyperlinkedModelSerializer):
    state = StateSerializer(read_only=True, context={'dt': self.context['dt']})

    class Meta:
        model = models.Object
        fields = ('state')

class StateSerializer(serializers.Serializer):
    dt = serializers.DateTimeField()
    ... other stuff...

As you can see I am trying to pass dt as extra context in the line state = StateSerializer(read_only=True, context={'dt': dt}) having set the context earlier in the view. The problem here is that when ObjectSerializer is initialized dt is not accessible via self.context['dt'] as self is not defined.

A: The solution is to make state a serializers.SerializerMethodField() and then define a get_state method. The new ObjectSeializer looks like this:
class ObjectSerializer(serializers.HyperlinkedModelSerializer):
    state = serializers.SerializerMethodField()

    class Meta:
        model = models.Object
        fields = ('state')

    def get_state(self, obj):
        state = obj.state(self.context['dt'])
        state_serializer = StateSerializer(state)
        return state_serializer.data


text:
Q: Filter JSON data with some column I have below json data.
I want to filter using url and skill and yyyy_mm column and create the new data in json format.
I have 2 requirements here:-
Using AND operator:

*

*filter using url column, yyyy_mm & skills column, suppose if i pass url as http://google.com and skills = C# and yyyy_mm = 2017-12
Just like sql - where yyyy_mm = '2017-10' and skills = 'C#' and url like '%google.com%'. Then it should return me all matching data.

Using OR operator:

*filter using url , yyyy_mm & skills column. So in this case whatever matching rows should be returned.
Just like sql - where yyyy_mm = '2017-12' and (skills = 'C#' OR skills = 'vb.net') and url like '%google.com%'. Then it should return me all matching data.

var tempData =[
  {"url":"http://google.com/shjj/player","yyyy_mm":"2017-12","skills":"C#","count":3},
  {"url":"http://google.com","yyyy_mm":"2017-12","skills":"C#","count":4}
  {"url":"http://google.com/jkl/uop","yyyy_mm":"2017-10","skills":"C#","count":4},
  {"url":"yahoo.com","yyyy_mm":"2017-12","skills":"vb.net","count":10},
  {"url":"yahoo.com","yyyy_mm":"2017-11","skills":"vb.net","count":5},
  {"url":"https://yahoo.com/player/fast","yyyy_mm":"2017-11","skills":"vb.net","count":6},
  {"url":"google.com/lope/fgkl","yyyy_mm":"2017-10","skills":"vb.net","count":10},
  {"url":"http://google.com/gog/blab","yyyy_mm":"2017-10","skills":"vb.net","count":11},
  {"url":"yahoo.com","yyyy_mm":"2017-10","skills":"json","count":100}
  {"url":"yahoo.com/onj/sfd","yyyy_mm":"2017-10","skills":"C#","count":200}
]

A: you can have a filter function like this

var tempData =[{"url":"http://google.com/shjj/player","yyyy_mm":"2017-12","skills":"C#","count":3},{"url":"http://google.com","yyyy_mm":"2017-12","skills":"C#","count":4},{"url":"http://google.com/jkl/uop","yyyy_mm":"2017-10","skills":"C#","count":4},{"url":"yahoo.com","yyyy_mm":"2017-12","skills":"vb.net","count":10},{"url":"yahoo.com","yyyy_mm":"2017-11","skills":"vb.net","count":5},{"url":"https://yahoo.com/player/fast","yyyy_mm":"2017-11","skills":"vb.net","count":6},{"url":"google.com/lope/fgkl","yyyy_mm":"2017-10","skills":"vb.net","count":10},{"url":"http://google.com/gog/blab","yyyy_mm":"2017-10","skills":"vb.net","count":11},{"url":"yahoo.com","yyyy_mm":"2017-10","skills":"json","count":100},{"url":"yahoo.com/onj/sfd","yyyy_mm":"2017-10","skills":"C#","count":200}]

function filter(filterObj, andOr) {
    if(andOr === 'and')
        return Object.keys(filterObj).reduce(function(arr, key) {
            return arr.filter(function(data){
                return data[key] === filterObj[key]
            })
        }, tempData)
    else
        return Object.keys(filterObj).reduce(function(arr, key, index) {
            return (index != 0 ? arr : []).filter(function(data) {
                return data[key] !== filterObj[key]
            }).concat(
            tempData.filter(function(data) {
                return data[key] === filterObj[key]
            }))
        }, tempData)
}

console.log("with 'or' operation", filter({count:4, yyyy_mm: "2017-10"}, "or"))
console.log("with 'and' operation", filter({count:4, yyyy_mm: "2017-10"}, "and"))
console.log("with single", filter({count:4}, "and"))

A: var result = [];
 getData("www.abcd.com","C#","1999-12");
function getData(url , skill , date){
   $.each(tempData,function(index,value){

     if(value.url == url && value.skills == skill && value.yyyy_mm == date ){
       result[index] = { url:value.url , skills:value.skills , yyyy_mm:value.yyyy_mm } ;
     }else if(value.url == url){
        result[index] = {url:value.url}
     }elseif( ....)
       ....
   })
}

I have given only example for AND operation and rest I have represented with ... as You just need to add coditions there in If and rest will work ....


text:
Q: How do I tell if the input has used duplicate letters? list = [ "A", "B" ,"C","T"]

I want to make a word from letters in a string. If the user inputs "cat" then that's correct, but if it's "CATT" then that's wrong. How would I detect that? The computer just sees if "A,B,C,T" is used but not how many times.

A: Well, you could use len(word) to get the length of the word, right?
Also, a set is a container of unique values. That is, you can't have the same value in a set more than once.
You can also pass a string into a set to fill the set with unique characters in the string.
Finally, you can take len(set) to get the number of unique items in the set.
So, if you add that all together:
>>> word = "CATT"
>>> len(word)
4
>>> my_set = set(word)
>>> my_set  # Sets aren't ordered, so it will probably come back in a different order
{'T', 'A', 'C'}
>>> len(my_set)
3

Huh, 3 != 4, right? It looks like in taking the unique values in "CATT", you had to throw one of them away because it was duplicated. Hey, convenient! So the short version is:
word = "CATT"
if len(word) != len(set(word)):
    print(word, "has duplicate letters")

Oh, and because this might answer your next question:
If you have two sets A and B, A <= B is True if and only if every item in A is also in B. For example:
>>> {1,2,3} <= {1,2,3,4}
True
>>> {1,2,3,4} <= {1,2,3}
False

Well, that's handy, because you can spell a word with a list of letters if and only if every letter in the word is also in the list of letters, right? And that looks a whole lot like the definition of A <= B! And indeed, it is:
>>> letters = ['a', 'b', 'c', 't']
>>> set('cat') <= set(letters)
True
>>> set('dog') <= set(letters)
False

Convenient, isn't it?

A: given:
lst = [ "A", "B" ,"C","T"]

word = "CAT"

there are many ways to accomplish this.
compare lengths
print(len([i for i in word if word.count(i.upper()) <= lst.count(i.upper())]) == len(word))

all method
print(all([word.count(i.upper()) <= lst.count(i.upper()) for i in word]))

an expanded variation on the all method
word = word.upper()

print(all([word.count(i) <= lst.count(i) for i in word]))

A: Simplest way would be to utilize any() function:
any([user_input.count(letter) > 1 for letter in your_list])

Would return True if any of the letters in your_list is repeated else False


text:
Q: Set Print Range in Numbers.app Is there any way to set a print range in Apple Numbers.app spreadsheets, to print just a subset of cells rather than entire document?

A: Apple's Numbers is designed in a fundamentally different way than Microsoft's Excel or other spreadsheet solutions.  Numbers uses "Canvases" instead of large tables of thousands of columns and rows.  This allows for placing tables, even those made up of a single cell, anywhere on the canvas needed.  Instead of merging cells and hiding borders, (which of course can be done with Numbers) Numbers allows more freedom to create a document designed for printing.  For example, placing text, charts or even graphics anywhere on the canvas that seems logical.  Setting the print range in Excel only allows for a continuous subset of cells.  Also, the ability to have several tables on a single canvas allows for more creative use of the space.  (See this Apple Support article on printing with Numbers.)
One can still use a very large data set in a large table as well.  However, this concept of making spreadsheets on canvases can open up many opportunities for print layouts.  The OP does not state how their spreadsheet is laid out, but it appears from the brief description that is styled in a traditional manner, which is perfectly acceptable, but this limits how it can be presented for printing.
One method I use, particularly with printing off invoice or expense type sheets, is to keep the working data on a separate sheet from my print sheet.  Using formulas, such as one would use in Excel, data can be easily and automatically
displayed in a printable format.
Below is a very simple example.  The Data sheet contains the data not for printing.  The [Print] sheet contains two simple tables with a colored rectangle object in the background.  Changing data in the Data sheet changes the totals in the Print sheet accordingly.  In the case of a traditional spreadsheet, a subset of the table could be displayed in the print sheet, each cell with a reference to the corresponding data sheet cells desired to be printed.  This table could then be formatted for printing by adjusting fonts, size and scaling as noted in the Apple Numbers Help link above.

Data Sheet [Non print]

Print Sheet

Print Sheet - Print view

A: Select the menu item File > Print, then use the controls on the right to scale the content:

A: Looking at the image in this answer, I got inspired to try something and what I discovered is that if you play with the "content scale", adjusting the percentage or sliding the scale's button, you can achieve the same effect as window's print range moving of the blue lines. I did have to delete a couple of rows (that were empty to begin with) to make 4 pages turn into 2), so its not as convenient as Window's blue lines, but one can still make it work :)

A: Copy the selection to the clipboard, then choose "New from Selection" in the Preview app. Job done!


text:
Q: Localstorage not storing URL I'm attempting to create a pop up modal with location options that redirect depending on user selection. I'm attempting to store the selected URL inside localstorage as a preference so that the user only has to choose their location once and not have to deal with pop ups every time they visit the site.
Every time I test this in browser the redirect is happening but when I enter a console.log to print out the localStorage value it's returning null I'm not getting any errors in the console so I don't have much to go off of.
My code is below and I've included a link to JS Fiddle here, any help is hugely appreciated!
    <div class="modal-body">
        <form name="siteSelector">
            <select onchange="save(); go()" id="site" name="site" SIZE="1" class="form-control form-control-lg">
                    <option value="non-value">Choose Site</option>
                    <option value="https://www.google.com">Google</option>
                    <option value="https://www.amazon.com/">Amazon</option>
                    <option value="https://www.guitarcenter.com/">Guitar Center</option>
            </select>
            <script>

                function save(){

                    document.getElementsByName("site").onchange = function(){
                        localStorage.setItem('site', document.getElementsByName("site"));
                    }

                    if (localStorage.getItem('site')) {
                        document.getElementsByName("site").options[localStorage.getItem('site')].selected = true;
                    }
                }

                function go(){
                    location = document.siteSelector.site.options[document.siteSelector.site.selectedIndex].value
                }

            </script>
        </form>
    </div>

A: You're trying to store a document element as localStorage item. You can store an index of selected option or URL.
In your sample document.getElementsByName returns NodeList - not a single element. Your save function can look like this:
function save () {
   let element = document.getElementById("site");
   if (!element.selectedIndex)
       return; // you can display error if that happens.
   localStorage.setItem('site', element.selectedIndex);
}


text:
Q: How to align the top of a view to half the parent view's height in Xcode 6.1 I am trying to align the top of the white subview to half the height of the container view in the viewcontroller. See attached image.
In old versions of Xcode it was possible to CTRL-drag from the view to the container view and select "top alignment with the container view", but in the new Xcode 6.1 they offer only alignment with the "TopLayout guide". So I used that constraint and setup the constraint as you can see in the right hand side of the image.
Based on my reading, the following equation applies:
property1 = property2 * multiplier + constant.
So I wanted to do this with my settings:
View.top = TopLayoutGuide.bottom * 0.5 + 0
such that the top of the white "View" aligns with half the height of the TopLayoutGuide.bottom.
However, when I do this, the result is that the ).5 is totally ignored, and the white view's top is aligned with the TopLayouGuide.bottom, covering the whole screen basically.
Can someone figure out what I am doing wrong, and what is the proper way to align the View's top to half the height of the container?
thanks
-Malena

A: I encountered the same problem with Xcode 6.1. I found that there are several ways to use only the storyboard editor to split a view (nearly) in half by adding a subview to use as a sort of benchmark. iMemon's programmatic solution works, but it requires additional code for constraints on any objects that use the halfway point as a reference, which can get tedious.
To solve your problem:

*

*Add another view to the controller's main view.

*Give it a color that stands out against its background.

*Give it a height of 1.

*Move it to the center of the main view and give it the "Vertical Center in Container" constraint.

*Now you can drag the top or bottom of any object to align with the frame of the view you just added. You can apply constraints by control+click+dragging from any object to the new view and selecting the appropriate constraint from the pop-up menu.

*Change the color of your benchmark view to something that will make it invisible in your application. I just used a clear color, as the object I wanted to align was also clear, and I had a background. If clear doesn't work for you, you could try constraining the width of the benchmark view to match the width of the object you aligned, then give them the same color.

You can extend this idea of using views as benchmarks to other situations, such as aligning with a point 3/4 the distance between two objects. You can add objects to views, apply constraints within those, and then move the views around and apply constraints in their superview as well. Get creative and experiment with it.

A: You can't achieve what you want to do in Interface Builder. But this is possible by creating constraints via code. I have created a sample project for you which you can download from Here
Below is the code of ViewController file to add constraints via code.
Note: I have added arbitrary constraints in Interface Builder since we need to get the main view height. Those are also important
//
//  ViewController.swift
//  Test
//
//  Created by FR-MAC on 11/12/14.
//  Copyright (c) 2014 ABC. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var mySubview: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.addContraintsForMoviePlayerView(self.mySubview, superView: self.view)

}

func addContraintsForMoviePlayerView(var view:UIView, superView:UIView) -> Void {

    view.setTranslatesAutoresizingMaskIntoConstraints(false)
    let leftConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0)

    let rightConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0)

    let bottomConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0)

    var topValue:CGFloat = superView.frame.size.height
    topValue = topValue/2

    let topConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view.superview?, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: topValue)

    // Remove the constraints created in Interface Builder to avoid autolayout constraint issues. We just added those constraints to get the correct height of self.view.frame which we used to create above topConstaint
    self.view.removeConstraints(self.view.constraints())

    //Add the above created constraints
    superView.addConstraints( [leftConstraint, rightConstraint, topConstraint, bottomConstraint] )
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

Hope this helps you :)


text:
Q: Explicitly allow traffic through Stingray Application Firewall I'm currently setting up a server for a customer and they require the Stingray traffic managers application firewall to be active as an additional layer of protection.
They're however wanting to allow any FTP traffic between the sizes of 500mb to 600mb straight through to the server and avoid the Application Firewall completely as to not be an additional drain on resources.
I've managed to find that the 'RequestWhitelist' parameter can be used within these rules by looking through the user manual (Page 55 if anyone's interested), however I'm having issues implementing this as I'm not too sure what type of syntax to use for this rule.
Also, forgive me if this is a basic question, however I didn't think it was possible to set a rule dependant on size, due to the fact that each packet will be only a few KB in size. However I can see that there is 'enforcer_max_body_size' within the WAF that will deny any requests with a body larger than X amount, however not sure where this would be picked up from and how I could use this within my rule.
Has anyone else had to configure anything like this within Stingray?


text:
Q: error with a java web service with a response type i am new here, the problem is that i want retrieve data from a third party web services, this web services come from another company, for the url i think that the web service was made in java ("http://javaee.ws.xxxx.com"), the problem is when i try to use a method of the web service, the method send a error and  say me that:
"The content type text/plain of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: '..."
i try to change this
  <basicHttpBinding>
    <binding name="xxxSoapHttp" useDefaultWebProxy="True" **textEncoding="utf-8"**/>
  </basicHttpBinding>

but the error persist....


text:
Q: Differences between behavior delegation approaches Could anyone explain differences between the following ways of composing objects in Javascript (ES6+)? Why and when should one be used over the other? I'd like to know arguments in favor and/or against each approach.
'use strict';
const foo = {
  say() {
    console.log('I say', this.message);
  }
};

const bar = {
  message: 'Hoo!'
};

// Method 1
const baz = Object.assign({}, foo, bar);
baz.say();

// Method 2
const baz2 = Object.assign(Object.create(foo), bar);
baz2.say();

// Method 3
const baz3 = Object.create(foo);
baz3.message = 'Heey!';
baz3.say();

// Method 4
Object.setPrototypeOf(bar, foo);
bar.say();

// Prints out:
// I say Hoo!
// I say Hoo!
// I say Heey!
// I say Hoo!

A: I'd like to try and take a shot at answering my own question, after some research.
All of the above approaches exemplify ways of implementing composition in Javascript.
Method 1 uses Object.assign() to create a type of cloning or concatenated prototype, often referred to as a mixin. No classical prototypal inheritance takes place.

Useful for handling state data or providing default values.

On method 2, Object.create() generates a delegate prototype which gets extended with additional properties after Object.assign(). Here, the resulting object's prototype points to foo.

Good for sharing functionality and methods between objects.

As Felix Kling correctly pointed out, method 3 is essentially the same as its predecessor.
Object.setPrototypeOf() on method 4 acts pretty much as Object.create() here, but instead of creating a new object, it changes the linkage of an existing bar object.
On this topic, "open source" book series You Don't Know JS expresses:

Ignoring the slight performance disadvantage (throwing away an object that's later garbage collected) of the Object.create(..) approach, it's a little bit shorter and may be perhaps a little easier to read than the ES6+ approach. But it's probably a syntactic wash either way.

For a more in depth analysis of this points, this 2013 talk by Eric Elliot goes a long way. His medium might also prove a good source.


text:
Q: Constraint check restrict null Oracle CREATE TABLE CLIENT
  (
    id       NUMBER (5) NOT NULL ,
    name      VARCHAR2 (20) ,
    surname  VARCHAR2 (20) ,
    company    VARCHAR2 (20) ,
ALTER TABLE CLIENT ADD CONSTRAINT CLIENT_PK PRIMARY KEY ( id ) ;

How to make check constraint that will forbid to enter company if name and surname are not null and opposite?

A: If I've understood your requirements correctly, then something like:
ALTER TABLE CLIENT ADD CONSTRAINT CLIENT_CK
check ( (company is null and name is not null and surname is not null)
        or (company is not null and name is null and surname is null) ) ;

E.g. out of the following insert statements, only the first two will successfully insert a row - the rest will fail due to the check constraint:
insert into client (id, name, surname, company)
values (1, 'fred', 'bloggs', null);

insert into client (id, name, surname, company)
values (2, null, null, 'ACME');

insert into client (id, name, surname, company)
values (3, 'joe', null, null);

insert into client (id, name, surname, company)
values (4, null, 'smith', 'INC INC.');

insert into client (id, name, surname, company)
values (5, 'bob', 'jobs', 'CORP CORP.');


text:
Q: if elif statement with & is giving unexpected output I am trying to learn python & while trying to solve this quiz on a website, I get a strange error , which is that the assertion fails for the 2nd parameter , while the if elif statement is correct & shall give the correct output (but it is giving a wrong unexpected output)
The error is:
"C:\Program Files\Python36\python.exe" C:/Users/.../PycharmProjects/pythonSnakegame/snakeGame.py
Fizz Buzz
Traceback (most recent call last):
Fizz Buzz
  File "C:/Users/..../PycharmProjects/pythonSnakegame/snakeGame.py", line 28, in <module>
    assert checkio(6) == "Fizz", "6 is divisible by 3"
AssertionError: 6 is divisible by 3

Process finished with exit code 1

def checkio(number):
    # Your code here
    # It's main function. Don't remove this function
    # It's using for auto-testing and must return a result for check.
    if number % 3 == 0 & number % 5 == 0:
        result = "Fizz Buzz"
    elif number % 3 == 0:
        result = "Fizz"
    elif number % 5 == 0:
        result = "Buzz"

    # replace this for solution
    print (result)
    return result
    # return str(number)

# Some hints:
# Convert a number in the string with str(n)

# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5"
    assert checkio(6) == "Fizz", "6 is divisible by 3"
    assert checkio(5) == "Buzz", "5 is divisible by 5"
    assert checkio(7) == "7", "7 is not divisible by 3 or 5"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

Thanks for your help

A: The & operator is for binary operations, you should use and (boolean operator) instead.

I kept wondering why it was not working

The & is disabling the module operation check for 5, so basically all divisible by 3 where getting True, check this output test:
number = 12
number % 3 == 0 & number % 5 == 0
True


text:
Q: Is function $ f(x)= e^{-(x+x^{2})} $ uniformly continuous on $R$ Is function $ f(x)= e^{-( x+ x^{2}) } $ uniformly continuous on $ R $?

As we know for any function $f$ which is continuous on $R$ and $ \lim_{ x\to  \infty} f(x)  $ ,  $ \lim_{x \to - \infty } f(x) $ exist finitely, then $ f$ is uniformly continuous.

I am confused about the limit of $f$ at $ - \infty $.
Please help.

A: $g(x)=-(x^2+x)=-(x+\frac{1}{2})^2+\frac{1}{4}$ $\Rightarrow$ $\lim_{x \to -\infty}g(x)=-\infty$
$\lim_{x \to -\infty}g(x)=-\infty$ $\Rightarrow$ $\lim_{x \to -\infty}e^{g(x)}=0$


text:
Q: Java and MiniMax with pruning I'm trying to implement a MiniMax algorithm with alpha/beta pruning. Totally stuck and can't see where I'm wrong. The class MiniMax contains a State and an Action. The method getAction returns an Action (supposedly the best action to take). The Game object has two methods, isTerminal returns true if the state is an "end state", ie there are no more children to that state. getUtility returns the value associated with an end state.
I'm trying to decide wheter it is Max or Min turn by using the counter round.
Currently the algorithm doesn't return the correct action, and at this stage I am just focussing on getting the expansion order right, getting the pruning bit to work.
public class MiniMax<State,Action> {

int alpha = Integer.MIN_VALUE;
int beta = Integer.MAX_VALUE;
int foundMax = 0;

int round = -1;
Action action = null;

public Action getAction(Game<State, Action> game, State state)
{
    round++;

    List<Successor<State, Action>> successors = (List<Successor<State, Action>>) game.getSuccessors(state);

    for (int i=0; i < successors.size(); i++)
    {
        if ( round % 2 == 0 )
        {
            if ( game.isTerminal(successors.get(i).state))
            {
                System.out.println("Max turn: Node: " + successors.get(i).state + ", utility: " + game.getUtility(successors.get(i).state) + ", alpha: " + alpha + ", beta: " + beta);
                alpha = Integer.max(alpha, game.getUtility(successors.get(i).state));
                if ( alpha <= beta )
                {
                    break;
                }

                action = successors.get(i).action;
            }
            if ( !game.isTerminal( successors.get(i).state) )
            {
                action = getAction(game, successors.get(i).state);
            }
        }
        else
        {
            if ( game.isTerminal(successors.get(i).state))
            {
                System.out.println("Min turn: Node: " + successors.get(i).state + ", utility: " + game.getUtility(successors.get(i).state) + ", alpha: " + alpha + ", beta: " + beta);
                beta = Integer.min(beta, game.getUtility(successors.get(i).state));
                if ( beta <= alpha )
                {
                    break;
                }

                action = successors.get(i).action;
            }
            if ( !game.isTerminal( successors.get(i).state) )
            {
                action = getAction(game, successors.get(i).state);
            }
        }
    }

    return action;
}

}


text:
Q: A measure theoretic problem related to induced representations I met such a rather concrete measure theoretic problem while dealing with induced representations of $p$-adic groups.
So let $G$ be a unimodular locally compact group, with $P$ its closed subgroup (what we think about them are just $p$-adic groups such as $G=GL(n,\mathbb{Q}_p)$ and $P$ its standard parabolic subgroups). Let $\delta_P$ be the module function of $P$ (coming from the difference of the left and right Haar measure on $P$). Let $C_c(P\backslash G,\delta_P^{-1})$ be the space of continuous functions $f:G\rightarrow \mathbb{C}$, such that the support of $f$ is compact modulo $P$, and
$$f(pg)=\delta_P(p)^{-1} f(g),~\forall p\in P,\forall g\in G.$$ Then we let $G$ act on this function space by right regular representation:
$$(R(g)f)(x):=f(xg).$$
O.K. So this is just a general construction in induced representations. By a very general theorem on Bushnell-Henniart's book, Local Langlands Conjecture for $GL(2)$, there is a $G$-invariant linear functional $\alpha:C_c(P\backslash G,\delta_P^{-1})\rightarrow \mathbb{C}$, namely $\forall f\in C_c(P\backslash G,\delta_P^{-1})$, we have $\alpha(R(g)f)=\alpha(f),\forall g\in G$.
What I want to ask is: suppose we have a compact open subgroup $K$ of $G$, such that $G=PK$ (this is the case for $GL(n)$ by Iwasawa decomposition), then how to prove
$$C_c(P\backslash G,\delta_P^{-1})\rightarrow \mathbb{C}, f\mapsto \int_K f(k)dk$$
is such a functional in that general theorem?
This seems to be very striking, because in the proof of the general cases, we don't have any idea how to write down such thing explicitly. I met this fact in Godement and Jacquet's classic "Zeta functions of simple algebras" (page 21), but I have no idea how to prove it. Can anyone give me some help? Thanks a lot in advance!

A: Ok, now I understand this crucial fact. Such a compact subgroup (with $G=PK$) is called a 'good compact'. It's proved in Casselman's famous notes (introduction to admissible representations of $p$ adic groups, subsection 3.1), for any such good compact, we have the above property. And this is very helpful in proving normalized induction preserves unitaricity.


text:
Q: How to include C++ library in Xcode I am migrating an Android application, which uses a C++ library to iOS.
C++ library provides main application functionality to the app. Is it possible to include a C++ library in XCode project?
I know that Apple LLVM compiler can compile C code, so a possible solution may be to compile C++ code into a shared library and then provide a C wrapper to be able to access C++ code from Objective-C. Similar solution was adopted with Android app and JNI.

A: Yes, you can.
There are two ways of doing this.
The easiest way would be to just add the sources inside your iOS project.
If you have the sources of the library , then you can add it to your project, just make sure to have your main file (and other objective C files) named from .m to .mm to let XCode now that you are compiling for C++.
If you want to go for static linkage, I strongly recommend to create a static library project and add it to the same workspace as your Objective C main project , then declare it as dependency for your build target (check build targets / build schemas ... XCode stuff over here :) ).
If you just want to provide a static library binary and just go with static linkage from there (which I really don't recommend , no breakpoints and some other pain along the way) then you have to keep in mind the following :

*

*you will need to have a separately compiled static library for each different platform (iOS simulator which is different from iPhone, arm64 , armv7 and armv7s ) and link accordingly

*an alternative to the above way is to make a fat lib (universal lib)

A: Look in the "Link Binary With Libraries" build phase under your target. Right click on it, and select "Existing Files..." -- then select the library you wish to link to. You don't have to use a framework as implied earlier.


text:
Q: How to print all values of an object methods? I have the output list of dir(requests) and I want to print all of the values.
Something like this:
from flask import Flask, request
for i in dir(request):
    print(i)
    print(request.i)

But it doesn't seem to work, please advise what I am missing?

A: i is a string here, you can't directly access methods like this, the getattr function is what has to be used:
for i in dir(request):
    print(i)
    print(getattr(request, i))


text:
Q: How to refer to children in a tree with millions of nodes I'm attempting to build a tree, where each node can have an unspecified amount of children nodes. The tree is to have over a million nodes in practice.
I've managed to contruct the tree, however I'm experiencing memory errors due to a full heap when I fill the tree with a few thousand nodes. The reason for this is because I'm attempting to store each node's children in a Dictionary data structure (or any data structure for that matter). Thus, at run-time I've got thousands of such data structures being created since each node can have an unspecified amount of children, and each node's children are to be stored in this data structure.
Is there another way of doing this? I cannot simply use a variable to store a reference of the children, as there can be an unspecified amount of children for each node. THus, it is not like a binary tree where I could have 2 variables keeping track of the left child and right child respectively.
Please no suggestions for another method of doing this. I've got my reasons for needing to create this tree, and unfortunately I cannot do otherwise.
Thanks!

A: How many of your nodes will be "leaf" nodes? Perhaps only create the data structure to store children when you first have a child, otherwise keeping a null reference.
Unless you need to look up the children as a map, I'd use a List<T> (initialized with an appropriate capacity) instead of a Dictionary<,> for the children. It sounds like you may have more requirements than you've explained though, which makes it hard to say.
I'm surprised you're failing after only a few thousand nodes though - you should be able to create a pretty large number of objects before having problems.
I'd also suggest that if you think you'll end up using a lot of memory, make sure you're on a 64-bit machine and make sure your application itself is set to be 64-bit. (That may just be a thin wrapper over a class library, which is fine so long as the class library is set to be 64-bit or AnyCPU.)


text:
Q: fail-safe cleanup (collections) warning after committing transaction with NHibernate When looking in NHProfiler I get following warning after committing my transaction:
fail-safe cleanup (collections) : NHibernate.Engine.Loading.CollectionLoadContext
I have absolutely no idea what this could be or how I can solve this. Can somebody help me?
Thanks,
Jelle

A: It's an NHibernate bug that you can ignore. I haven't noticed it since I upgraded NHIbernate to 2.1.2.GA.


text:
Q: Django - how to write users and profiles handling in best way? I am writing simple site that requires users and profiles to be handled. The first initial thought is to use django's build in user handling, but then the user model is too narrow and does not contain fields that I need. The documentation mentions user profiles, but user profiles section has been removed from djangobook covering django 1.0 (ideally, the solution should work with django 1.2), and the Internet is full of different solutions, not making the choice easier (like user model inheritance, user profiles and django signals, and so on).
I would like to know, how to write this in good, modern, fast and secure way. Should I try to extend django builtin user model, or maybe should I create my own user model wide enough to keep all the information I need? Below you may find some specifications and expectations from the working solution:

*

*users should be able to register and authenticate

*every user should have profile (or model with all required fields)

*users dont need django builtin admin panel, but they need to edit their profiles/models via simple web form

Please, let me know how do you solve those issues in your applications, and what is the best current way to handle users with django. Any links to articles/blogs or code examples are highly appreciated!

A: Seems to me like the current version of the Django docs and the Django book both have sections for this.

*

*http://docs.djangoproject.com/en/dev/topics/auth/#auth-profiles  talks about using AUTH_PROFILE_MODULE to specify the model class that will store extra user information

*http://www.djangobook.com/en/1.0/chapter12/#cn222  as does this

A:
users should be able to register and authenticate

django.contrib.auth is the module you want.  Be sure to check the docs for custom login forms.

every user should have profile (or model with all required fields)

You need to set settings.AUTH_PROFILE_MODULE, as noted by others.
Information about setting up the user profile model is available for the latest version, 1.1, and 1.0.  It hasn't been dropped.

users dont need django builtin admin panel, but they need to edit their profiles/models via simple web form

You can create a form and view just like you would for any other app; maybe make a "user control panel" app for handling these things.  Your views would then interact with the django.contrib.auth.models.User and django.contrib.auth.models.Group models.  You can set this up to do whatever you need.
EDIT: Responding to your questions-in-the-form-of-an-answer (paging Alex Trebek)...

The second version of djangobook, covering django 1.0 (that is way closer to 1.2 than 0.96) no longer has that information anywhere, what makes me highly confused - has anything changed? Is there other, better, more secure way to handle users and their profiles? Therefore this question asked.

I wouldn't recommend djangobook as a reference; it's out of date on this topic.  User profiles exist and I'm using them in my Django 1.1.1 site; I'm even populating them from NIS.
Please use the links I provided above.  They go directly to the actual Django documentation and are authoritative.

By the way, I forgot to ask, if the way you all refer to (that is AUTH_PROFILE_MODULE) will create automatically upon registration

Answered in the docs.

and require the profile to exist upon any action (user withoud existing, filled profile should not exists, this is why I was thinking about extending User model somehow)?

The profile needs to exist if User.get_profile() is called.

Will it get updated as well (people are mentioning 'signals' on various blogs related to this subject)?

It's like any other model: it only gets updated when you change the fields and call save().
The signal part is how you hook in a function to create a profile for a new User:
from django.db.models.signals import post_save
from django.contrib.auth import User
from myUserProfileApp import UserProfile

def make_user_profile(sender, **kwargs):
    if 'created' not in kwargs or not kwargs['created']:
        return

    # Assumes that the `ForeignKey(User)` field in "UserProfile" is named "user".
    profile = UserProfile(user=kwargs["instance"])
    # Set anything else you need to in the profile, then...
    profile.save()

post_save.connect(make_user_profile, sender=User, weak=False)

This only creates a new profile for a new User.  Existing Users need to have profiles manually added:
$ ./manage.py shell
>>> from django.contrib.auth import User
>>> from myUserProfileApp import UserProfile
>>> for u in User.objects.all():
...  UserProfile(user=u).save() # Add other params as needed.
...

If you have some users with profiles and some without, you'll need to do a bit more work:
>>> for u in User.objects.all():
...  try:
...   UserProfile(user=u).save() # Add other params as needed.
...  except:
...   pass

A: Django supports a UserProfile model (of your own creation) right out of the box.  You can assign this in your settings.py file with: AUTH_PROFILE_MODULE.  That being said, I will agree with you that it is a little confusing at first.
How I handled it was to create my own UserProfile model with the fields I wanted and hook it into the Django User model via the settings (above).  I believe this is the preferred way and probably better than extending the base User model.
You can access your profile through User.get_profile().
There are a couple projects on github that are UserProfile oriented.  If you wanted some code examples, you could look there.

A: Thank you all for your answers! I know that django dev documentation mentions user profiles, but does it very briefly (roughly few lines) and links to djangobook containing information about user profiles, but... to its first version, covering django 0.96. The second version of djangobook, covering django 1.0 (that is way closer to 1.2 than 0.96) no longer has that information anywhere, what makes me highly confused - has anything changed? Is there other, better, more secure way to handle users and their profiles? Therefore this question asked.


text:
Q: Text got blurred on Android Webview I'm developing a web based app.  I load a page on an android WebView.
The issue is, I set a wave border effect to a div using css3 radial gradient, the page shows correctly on most browsers, and works fine for iOS version app as well.  But on the android app, If I add this style, the page will totally become blurred.  I paste my css code here:
wave-l:before{
    display: block;
    position: absolute;
    content: '';
    top: 0px;
    left: -4px;
    height: 100%;
    width: 4px;
    background-position: 0px 0px;
    background-size: 4px 8px;
    background-image: -webkit-radial-gradient(100% 4px, circle, $color 4px, transparent 4px);
    background-image: -moz-radial-gradient(100% 4px, circle, $color 4px, transparent 4px);
    background-image: radial-gradient(circle at 100% 4px, $color 4px, transparent 4px);
}

This css will generate a left wave style border.  The blurred pages shown on android WebView is as shown below:

I'm quite sure it's this css code snippet caused the issue.  So anybody know the solution?

A: Add  the code
  android:hardwareAccelerated="false"

in the AndroidManifest.xml  webview used activity.

A: It is too late to respond, but I was also getting the blurred issue in webView. I resolved it by adding
webView.getSettings().setJavaScriptEnabled(true);

It may help somebody


text:
Q: jQuery $.on() isnt listening to custom native js event I'm trying to have jQuery listen to an event that is not triggered by jQuery.
Here is the listener:
 $(document).on("end.eTime", function (e) {
   console.log("here");
   $("body").append(e.name + " " + e.ellapsed + "<br>");
 });

Here is the trigger:
var event= new CustomEvent('end.eTime', {custom: object})
document.dispatchEvent(event);

Using newest firefox to test.
If I trigger using jQuery's trigger it works fine, but I'm trying to write a pure js library.
If I try to listen with a native listener it works fine, but I would like to allow users of my library to use jQuery.
Can anyone tell me why jQuery $.on() doesnt want to listen to a native custom event?
Update
So I removed the namespace as @Derek suggested and then jquery will listen for it correctly. I believe this is a bug so I submitted it here:http://bugs.jquery.com/ticket/15143.
I also found, as expected, that native listeners cannot hear jquery events. As @kcent said, they use a completely different process, so its no wonder it doesnt work. The documentation says that it still calls the native events, but this is probably only for things like click. This doesnt effect me for this process, but I still mention in the ticket that it would be nice if it worked.
For a whole series of examples you can check the ticket on jquery.

A: jQuery uses it's own internal event registry to keep track of the events that are set & triggered. So, when you created a custom event using native JS, it side-steps that pattern and jQuery doesn't know about it.
If you want to support both, you will likely need to create some custom event methods that register a listener in both native JS and jQuery.
Also side note CustomEvent is not available below IE9, if that's a concern for you.
Great reference on custom events: http://www.sitepoint.com/javascript-custom-events/

A: I have a feeling this has to do with the namespace declaration. This works for me with jQuery 2.1 if I name the event 'eTime' instead of 'end.eTime'.
That being said, why wouldn't you use jQuery to trigger the event?


text:
Q: on image hover adds a spacing to the left My Site - Product Grid
When you hover over either of the product images on this page, there is a 2px horizontal line that appears to the left.  I tried setting my padding, margin, no-wrap, I just can't figure it out.  Thanks for looking and any advice.
I know I can cheat it by adding:
.mz-productlisting-image img {
    margin-left: -4px;
}

But I don't want to if I don't have to!

A: This is the text-decoration:underline; of the anchor tag.
Simply add to
.mz-productlist-tiled a:focus,
.mz-productlist-tiled a:hover{
    text-decoration:none;
}

Hope it helps :)


text:
Q: Get the NEXT value in an array in BigQuery I want to get the next value in an array delimited by "->"
For example, in this example below, i want to get the next value after "Res" in each
ROW 1- "Q -> Res -> tes -> Res -> twet"
ROW 2- "rw -> gewg -> tes -> Res -> twet"
ROW 3- "Y -> Res -> Res -> Res -> twet"

Output would be:
ROW 1- tes
ROW 2- tewt
ROW 3- tewt

Ive tried the following but it gets me the previous value,
Array_reverse(split(regexp_extract(COLUMN_NAME, '(.*?)Res'), '->'))[safe_offset(1)]

A: Consider below approach
select id,
  ( select word from unnest(arr) word with offset
    where offset > (select offset from unnest(arr) word with offset where trim(word) = 'Res' limit 1)
    and trim(word) != 'Res' order by offset limit 1
  ) as next_word
from your_table, unnest([struct(split(path, '->') as arr)])

if applied to sample data in your question - output is

Another option is
select id,
  ( select split(pair, ' -> ')[offset(1)]
    from unnest(arr) pair with offset
    where trim(pair) != 'Res -> Res'
    order by offset limit 1
  ) as next_word
from your_table, unnest([struct(regexp_extract_all(path, r' Res -> \w+') as arr)])

with same output
The benefit of later solution is that it can easily be adjusted to catch all instances (in one row) of words placed after 'Res' - like in below example
select id,
  array( select split(pair, ' -> ')[offset(1)]
    from unnest(arr) pair with offset
    where trim(pair) != 'Res -> Res'
    order by offset
  ) as next_words
from your_table, unnest([struct(regexp_extract_all(path, r' Res -> \w+') as arr)])

with output

A: Consider the approach below using distinct to remove the duplicates and will retain the 1st occurence:
with sample_data as (
          select 'ROW 1'as id, "Q -> Res -> tes -> Res -> twet" as test_str
union all select 'ROW 2'as id ,"rw -> gewg -> tes -> Res -> twet" as test_str
union all select 'ROW 3'as id, "Y -> Res -> Res -> Res -> twet" as test_str
),
remove_dups as (
select
  id,
  array_to_string(array(select distinct * from unnest(split(test_str,' -> '))),',') as clean_str
from sample_data
)
select
  id,
  regexp_extract(clean_str,r',?Res\,(\w+)\,?') as next_word
from remove_dups

Output:


text:
Q: How to create an offset for the text displayed in an input? I am creating a basic log in function, really nothing fancy.

this is what I have right now, but this is what I would like to have:

I don't just want to add spaces, since, when the user clicks the input field it clears the input. But I don't just want to clear it to another space as the user would be able to delete that then. I want a premade property to have that little one space-offset on the left, preferably ignored if I evaluate the input later on.
Thanks in advance.

A: Use
input{ padding-left: 10px; }

A: Using css padding-left on your input  , see below snippet :

.login-input {
  padding-left:10px;
}
<input class="login-input" type="text" placeholder="enter username" />

<input class="login-input" type="text" placeholder="enter password" />

A: Did you try padding :

.username
{
  padding-left : 10px;
}
<input type = 'text' class='username' value='Enter username'>

A: Use padding property to input.

input{
padding-left:10px;
}
<input type="text" value="this is sample text"/>

A: I think that I understand what you want:
You need that help text please enter your user name... to be blank when the user click on the input field ?!
TO DO SO :
<input type="text" name="username" placeholder="please enter your user name..."/>


text:
Q: How to set input cloud for pcl::BoxClipper3D My pcl version is 1.8.
I plan to use pcl::BoxClipper3D to remove the points inside a box.As there is an angle between the box and the x-axis of point cloud, pcl::cropbox cannot used directly.So I choose pcl::BoxClipper3D.
However there is no member method to set input cloud because it not inherit from Filter.
So anyone have idea to use pcl::Boxclipper3D to filter points inside a certain box?


text:
Q: Reference seemingly not working, no apparent error thrown I have superficial knowledge on referencing libraries in projects. Usually most of the time a simple 'add reference' and then browsing to the appropriate path, just works. I am following an issue I will try to explain , and show all the approaches I tried to tackle it.

I am trying to use AutoIt. In their website it is stated that simply adding the .dll and using it, is enough to integrate their functionality in visual studio.
I am doing just that but for the moment I can not get my head around what is happening.
AutoItX is a public static class, as also the Run function is the same (public static). After adding the reference I can navigate to the appropriate .cs (if I control click on it for example). So the class AutoItX is not something unknown for the project. Moreover, the function Run indeed exists

however not inside the project itself. AutoItX also needs staff from (dont know if it is important):

The main error is that AutoItX doesnt exist in this context.
I have tried to register the dll, I have tried to add the com reference and remove it, I have tried to move the .cs files inside the project. None of those corrected the issue.
Any help would be valuable. If I missed something and you need extra info, I am willing to provide it. (Latest vs, latest autoit version, .net framework type of project).

A: Actually the above works.
For future reference.
The reason I did not try it first was, that they propose in their website to reference the autoItX.assembly.dll. This is probably deprecated and does NOT work anymore.
Second, if you have already referenced it , downloading this from NuGet WONT fix it.
Finally, the NuGet package does NOT work with .net CORE but ONLY with .net Framework project

A: I installed AutoItX.Dotnet 3.3.14.5, my test is no problem.
You can refer to my steps to create a new project to test it.
Right click  References=>Manage NuGet Packages=>Browse=>AutoItX.Dotnet=>Install

Running result:


text:
Q: Calculation of probability of selling a Poisson number of products You sell 10 product on average every day. The model is based on a Poisson distribution.
To be enable to cover the indirect cost, the manager needs to sell 8 products per day.
Two questions:

*

*What is the probability to sell between 0 - 5 products in a day?

*What is the probability to have at least 6 products in a single day?

A: For a random variable $X \sim \textrm{Poisson}(\lambda)$, the probability of seeing a value of $k$ is:
$$
P_k = \frac{e^{-\lambda} \lambda^k}{k!}
$$
So the probability of selling less than or equal to $5$ products in a given day, where the long-term average is $8$ is:
$$
P_{0\ldots5}=\sum_{i=0}^5\frac{e^{-8} \lambda^i}{i!}
$$
The probability of at least $6$ is everything other than $0$ to $5$ or $(1-P_{0\ldots5})$ for which you were asked in the first part.

A: You can calculate the probabilities manually or you can do it with R. The code for the cumulative distr. of Poisson is ppois(k,m), k being the limit $P(X\leq k) $ and m the parameter of the distribution.


text:
Q: how can we represent the following projection how can we express the following correctly.
$$f:E\to F  $$
$$E \subseteq C_1 \times C_2 \times C_3 \times C_4 $$
$$f|_A:A\to F$$
$$A \subseteq C_1 \times C_4 $$
here, I misused the notation of mathematical restriction.
I am looking for some notation like $f|_A$


text:
Q: How to get the label builder not to force downcase everything? when I'm using the label helper in a form contex, the label is getting downcased. Can I change this behavior?
example:
produce: "Things are getting big" but I want "Things Are Getting Big"
using rails 2.3

A: See documentation. First parameter for the label is the name of the field it references, not label's text. If there is no text provided, it uses field's name (localized/humanized)
Your label code produces
Things are getting big

And you possibly need
Things are getting big

You can do that with:
<%= f.label :field_name, "Things Are Getting Big" %>


text:
Q: Openedx import fails with "'NoneType' object has no attribute 'data_dir'" message I created a course on my personal openedx instance. Then exported it, and tried to import it into an institutional platform but got the error :
There was an error while importing the new course to our database.
'NoneType' object has no attribute 'data_dir'

enter image description here
How to solve this ?

Edit: also, duplicated sections are not exported properly. You must create them my click on the create button, then move relevant content into those.

A: You need to fix some minor issue in the archive.
Within your archive, edit /course/policies/course/policy.json.
Somewhere within it there is a tabs object.
"tabs": [
      {
        "course_staff_only": false,
        "name": "Home",
        "type": "course_info"
      },
      {
        "course_staff_only": false,
        "name": "Course",
        "type": "courseware"
      },
      ...
]

Within it, the type courseware whould be first.
"tabs": [
      {
        "course_staff_only": false,
        "name": "Course",
        "type": "courseware"
      },
      {
        "course_staff_only": false,
        "name": "Home",
        "type": "course_info"
      },
      ...
]

Import then works :
enter image description here


text:
Q: Qt Quick 2.2 Application: Choosing component set step I am creating a new Qt Quick application in Qt 5.3 for the first time. I would like to have the latest controls available.
When prompted to select a "Component Set" my dropdown options are : Qt Quick 2.0/2.1/2.2, and Qt Quick Controls 1.0/1.1.
What is the difference between the "Qt Quick" and "Qt Quick Controls" options? Which is the "latest and greatest?"
Thanks in advance.

A: If you'd like to have the latest controls available, you should pick the Qt Quick Controls 1.1 option. This will set up an ApplicationWindow-based application for you.
The difference between the two:

*

*Qt Quick is the basic-yet-powerful set of building blocks that allows you to create applications where a notion of a native look and feel is not important.

*Qt Quick Controls provide the Qt Quick equivalent of widgets, but with a styling API that is much more user-friendly.

Creating Qt Quick UI Projects says:

The Qt Quick imports enable you to create cross-platform applications with a custom look and feel, whereas the Qt Quick Controls provide the look and feel for a particular platform

It is worth mentioning that the styling API also allows you to intentionally create controls that don't look native. For that reason, I'd always recommend picking the Qt Quick Controls component set, as you get a lot of stuff (including Layouts) that is really useful.


text:
Q: Pass makefile automatic variable value to bash function called from make Say I have the following function defined in my .bashrc:
foo (){
    touch $1
    }

I want to call this function in a makefile like so:
%.png : %.tex
    bash -i -c foo $<

But this complains about a missing operand. (The error is "touch: missing file operand", so it is calling touch...). I've seen some solutions to similar issues, but they aren't applicable since I need the automatic variable $< (or rather, its value) to be passed as an argument to the shell script.
I know I could work around this problem (copy the function wholesale into the makefile, for example) but I'm curious to see how I could solve my problem within the makefile.

A: Your problem is probably because you don't have enough quoting.  The shell -c option takes its script as a single argument.
Consider:
$ bash -c echo hi
<prints nothing>

Versus:
$ bash -c 'echo hi'
hi


text:
Q: c# DataGridView bound to DataTable - How to add character to double-only column? I've got DataGridView bound to a DataTable with some numeric data and I need two things to ensure are working:

*

*Numeric sorting (doubles/ints) on every column with numbers,

*Possibility to add some text (like 'x' or '-') instead of numbers in special cases.

Is there a simple way I could add them at the level of DataTable?
I know I can change type of DataTable's columns to String, but then I'd need to add much more code just for the sake of sorting columns by already built-in way - and I certainly don't need to change the way glyphs are drawn, etc.
Also, because of amount and way my DGVs are spawned, it won't be as easy as adding one method for every DGV I've got.
[Edit]
I write the same set of DataTables to excel files, so drastic changes to the way they work would be problematic and error prone - I'd like to avoid it.
My code for filling dataTables in most occasions looks like this:
var row = MyDataTable.GetMyDataTableNewRow();
row.partName = part.name;
row.weight = part.weight.ToString();  // it's double
row.quantity = part.GetParentSet().FindQuantities(part.name).ToString(); // it's int
row.maxsize = part.CalculateMaxSize().ToString();
MyDataTable.AddMyDataTableRow(row);

A: The only way to define you desired behaviour at DataTable level, is introducing a custom type holding both a double and a string, and defining an appropriate TypeConverter (to correctly show the objects and enable editing in the DataGridView).
e.g. :
[TypeConverter(typeof(DoubleOrTextConverter))]
public class DoubleOrText : IComparable
{
    public double Value { get; private set; }
    public string Text { get; private set; }
    public DoubleOrText(double val, string text)
    {
        this.Value = val;
        this.Text = text;
    }
    public static DoubleOrText FromString(System.Globalization.CultureInfo culture, string str)
    {
        double v;
        if (double.TryParse(str, out v))
            return new DoubleOrText(v, null);
        return new DoubleOrText(0, str);
    }
    public string ToString(System.Globalization.CultureInfo culture)
    {
        if (this.Text != null)
            return this.Text;
        return this.Value.ToString(culture);
    }
    // define your sorting strategy here
    public int CompareTo(object obj)
    {
        if (obj == null) return 1;

        var other = obj as DoubleOrText;
        if (other != null)
            return this.Value.CompareTo(other.Value);
        else
            throw new ArgumentException("Object is not a DoubleOrText");
    }
}

public class DoubleOrTextConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
            return true;
        return base.CanConvertFrom(context, sourceType);
    }
    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value is string)
            return DoubleOrText.FromString(culture, value as string);
        return base.ConvertFrom(context, culture, value);
    }
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            var dValue = (DoubleOrText)value;
            return dValue.ToString(culture);
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

Usage example:
DataTable dt = new DataTable();
dt.Columns.Add("Column 1", typeof(DoubleOrText));

dt.Rows.Add(new DoubleOrText(0.0, null));
dt.Rows.Add(new DoubleOrText(1.0, "X"));
dt.Rows.Add(new DoubleOrText(2.3, "-"));
dt.Rows.Add(new DoubleOrText(4.1, null));

this.dataGridView1.DataSource = dt;

Result:

A: With the DataGridView you can apply formatting at the UI level that handles the case where you and to specially change some values in a numeric column without altering the column to text.
This is achieved using the CellFormatting and CellParsing events of the DataGridView.
Say for example you have an int column in your data table and you want to display all instances of 1 as an x and all instances of 3 as a y.
You use the CellFormatting event like so:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (dataGridView1.Columns[e.ColumnIndex].Name == "CustomerID")
    {
        if (int.Parse(e.Value.ToString()) == 1)
        {
            e.Value = "x";
        }
        else if (int.Parse(e.Value.ToString()) == 3)
        {
            e.Value = "y";
        }
    }
}

With this approach the underlying data table is untouched as are the underlying cell values, so formatting still works as though you had the numbers 1 and 3.
You then will need to do some processing within the CellParsing event to convert the strings back. This again is because your underlying table still has a numeric column.
Something like the following simply uses the actual value of the cell in the case where the value being parsed does not convert to an int. You can however, do anything you need in this handler:
void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
    int parsedValue = 0;
    if (!int.TryParse(e.Value.ToString(), out parsedValue))
    {
        if (int.TryParse(dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString(), out parsedValue))
            e.Value = parsedValue;
        else
            e.Value = 0;

        e.ParsingApplied = true;
    }

}


text:
Q: What do I do when pg_cancel_backend doesn't work? If I have a long-running Postgres query, and regular "kill [pid]" doesn't work, and pg_cancel_backend doesn't work, what should I do?

A: You should never kill -9 any postgres process unless your goal is to bring the entire server down forcibly.  You can kill any process that doesn't respond to a pg_cancel_backend() call from the shell with
kill <pid>

i.e. not -9.  Note that I have seen a few times where even that didn't work due to the process being hung waiting in some loop for data on a network connection.  If I recall correctly, killing the client process took care of that.

A: if you have a recent Postgres you can try pg_terminate_backend instead.

A: http://www.postgresql.org/docs/current/static/server-shutdown.html
pg_cancel_backend is equivalent to sending SIGINT to the process.
pg_terminate_backend likewise for SIGTERM, but if pg_cancel_backend isn't working I don't see why pg_terminate_backend would.
If you've tried those options, you could try SIGQUIT.  The docs say, "This is recommended only in emergencies."
(If you hate your data and hope it dies, you could use SIGKILL.  But I wouldn't.)
You can use either kill directly or pg_ctl kill.

A: bribles is correct in his statement above...
IF you are trying to SHUTDOWN the server, for me though:
I'm just trying to remove retired Databases/Schemas,
that still have a lingering connection that it won't let go of.
So, to answer your question,

If I have a long-running Postgres query ...
pg_cancel_backend doesn't work...
what should I do?

NOT RELATED to shutting down the server in any way.
I have also seen this behavior of pg_cancel_backend() not working.
And wanted to share my working solution.
I have not seen an issue thus far, with any kind of "loss" of data.
Again, I'm not trying to kill Active queries either.

-- I'm logged into as USER "A"  with a session or PID of 777777.
-- And going to try and force disconnect another session from USER "A" open as 123456789
-- Which is a sleeping connection, and is why I also look for idle in my queries below.

SELECT *
FROM pg_stat_activity
WHERE pid = 123456789
      AND STATE = 'idle';

-- Attempt 1

SELECT pg_cancel_backend(pid)
FROM pg_stat_activity
WHERE pid = 123456789
      AND STATE = 'idle';

-- Interestingly enough Result states that the cancellation is TRUE but still exists.

SELECT *
FROM pg_stat_activity
WHERE pid = 123456789
      AND STATE = 'idle';

-- Attempt 2

SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE pid = 123456789
      AND STATE = 'idle';

-- And Now it doesn't exist..

SELECT *
FROM pg_stat_activity
WHERE pid = 123456789
      AND STATE = 'idle';

-- NOTE: I tried to use ridiculous pid #'s to help prevent people from copying & pasting and wrecking their lives.
-- NOTE: By default postgres will ONLY allow you to kill processes running under YOUR logging in USER,
-- NOTE: but you knew that already.

Hope this helps. =)
~Jay


text:
Q: How to do "group by / max" query? I need to group all records by a value of Field1, and calculate max value of Field2 for every group. So, is there any way to make max aggregation work over multiple groups within the same query?

A: GET /yourindex/_search?search_type=count
{
  "aggs": {
    "yourGroup": {
      "terms": {
        "field": "field1",
        "size": 10
      },
      "aggs": {
        "theMax": {
          "max": {
            "field": "field2"
          }
        }
      }
    }
  }
}


text:
Q: convert csv data to dict without writing file to disk Here is my scenario: I have a zip file that I am downloading with requests into memory rather than writing a file. I am unzipping the data into an object called myzipfile. Inside the zip file is a csv file. I would like to convert each row of the csv data into a dictionary. Here is what I have so far.
import csv
from io import BytesIO
import requests

# other imports etc.

        r = requests.get(url=fileurl, headers=headers, stream=True)
        filebytes = BytesIO(r.content)

        myzipfile = zipfile.ZipFile(filebytes)
        for name in myzipfile.namelist():
            mycsv = myzipfile.open(name).read()
            for row in csv.DictReader(mycsv):  # it fails here.
                print(row)

errors:
Traceback (most recent call last):
  File "/usr/lib64/python3.7/csv.py", line 98, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not int (did you open the file in text mode?)

Looks like csv.DictReader(mycsv) expects a file object instead of raw data. How do I convert the rows in the mycsv object data (<class 'bytes'>) to a list of dictionaries? I'm trying to accomplish this without writing a file to disk and working directly from csv objects in memory.

A: The DictReader expects a file or file-like object: we can satisfy this expectation by loading the zipped file into an io.StringIO instance.
Note that StringIO expects its argument to be a str, but reading a file from the zipfile returns bytes, so the data must be decoded.  This example assumes that the csv was originally encoded with the local system's default encoding.  If that is not the case the correct encoding must be passed to decode().
for name in myzipfile.namelist():
    data = myzipfile.open(name).read().decode()
    mycsv = io.StringIO(data)
    reader = csv.DictReader(mycsv)
    for row in reader:
        print(row)

A: dict_list = [] # a list
reader = csv.DictReader(open('yourfile.csv', 'rb'))
for line in reader: # since we used DictReader, each line will be saved as a dictionary
 dict_list.append(line)


text:
Q: Using Facebook advertising tracking pixels in Angular 2 / 4 I'm trying to work out how I use the Facebook tracking pixel with my angular project.
I have added the base pixel into my index.html
but I want to fire an event from the javascript, how do I fire this
fbq('track', 'CompleteRegistration');

Angular will not compile when I have this in my code as it can't find fbq

A: Even though fbq is globally-available in your app at runtime, the compiler doesn't know about it because it is defined in index.html (outside of the typescript files known to the compiler).
To fix this, add an ambient declaration to the files where you use fbq, like so:
declare const fbq: any; // 1. add an ambient declaration

@Component({...})
export class ComponentUsingFacebookPixel {

  fbq('track', 'CompleteRegistration'); // 2. This will compile now

}

This doesn't change the compiled javascript or overwrite the value of fbq; it's a promise to the compiler that there will be a value by that name available at runtime.
You can provide a more specific type than any if you'd like additional help from the compiler, but any is sufficient to avoid the compilation error you're seeing.

A: create one service and call it in your app.component.ts
import { Injectable } from '@angular/core';

    @Injectable({
        providedIn: 'root'
    })
    export class FacebookPixelService {
        constructor() { }
        load() {
            (function (f: any, b, e, v, n, t, s) {
                if (f.fbq) return; n = f.fbq = function () {
                    n.callMethod ?
                        n.callMethod.apply(n, arguments) : n.queue.push(arguments)
                }; if (!f._fbq) f._fbq = n;
                n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
                t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
            })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
            (window as any).fbq.disablePushState = true; //not recommended, but can be done
            (window as any).fbq('init', '<your id>');
            (window as any).fbq('track', 'PageView');
        }
    }

A: add this in ngOnInit() if you have already added to index.html
(window as any).fbq('track', 'CompleteRegistration'); // this Worked for me