text:
Q: SUDS: Pass Array Parameter in Client.service Method : GAE Python In one of my application am consuming SUDS WSDL(SOAP) web services at GAE python.
My Py Code:
url = 'http://203.215.51.43/Gateway/Execute?WSDL'
client = Client(url)
print client

So it printing at server console
Suds ( https://fedorahosted.org/suds/ )  version: 0.4 GA  build: R699-20100913
Service ( GatewayService ) tns="urn:fks:jcaps:gateway"
   Prefixes (2)
      ns0 = "http://fks.com/gtwy"
      ns1 = "urn:fks:jcaps:gateway:JavaException"
   Ports (1):
      (Execute)
         Methods (1):
            redeem(xs:string SessionId, xs:string TerminalId, xs:string StoreCod
e, xs:string CashMemoNo, xs:string CashMemoDate, xs:double InvoiceAmount, xs:str
ing TimeStamp, xs:string CashierId, xs:string MerchantId, ns0:SPCReqDtls SPCReqD
tls, ns0:VoucherReqDtls[] VoucherReqDtls, ns0:CardReqDtls CardReqDtls, )
         Types (1):
            ns1:JavaExceptionType

Actually am able pass string, double type values in redeem method but not an array/list type,
result = client.service.redeem(SessionId=result['SessionId'], StoreCode='4739', TerminalId='T1081', TimeStamp='01-01-2011 01:01:00.000')

But am not able to pass here VoucherReqDtls array
the WSDL's XML code of this VoucherReqDtls is as below,
    <!--Zero or more repetitions:-->
             <gtwy:VoucherReqDtls>
                <gtwy:VoucherType>GV</gtwy:VoucherType>
                <!--1 or more repetitions:-->
                <gtwy:VoucherReq>
                   <gtwy:VoucherNo>344234242</gtwy:VoucherNo>
                </gtwy:VoucherReq>
                <gtwy:VoucherReq>
                   <gtwy:VoucherNo>675685858</gtwy:VoucherNo>
                </gtwy:VoucherReq>
             </gtwy:VoucherReqDtls>

So how can i pass the VoucherReqDtls array/list in redeem method, here VoucherType is GV and count of VoucherNo could be more than one.

A: I think the issue is that the redeem method, if you visually inspect the WSDL, expects a complex type of GatwayReq which can be created with the following code :
>>> it = client.factory.create('ns0:GatewayReq')
>>> it
(GatewayReq){
   SessionId = None
   TerminalId = None
   StoreCode = None
   CashMemoNo = None
   CashMemoDate = None
   InvoiceAmount = None
   TimeStamp = None
   CashierId = None
   MerchantId = None
   SPCReqDtls =
      (SPCReqDtls){
         SPCNo = None
         SPCAmt = None
      }
   VoucherReqDtls[] = <empty>
   CardReqDtls =
      (CardReqDtls){
         CardType = None
         CardReq =
            (CardReq){
               CardNo = None
               TransAmt = None
            }
      }
 }

you can add the elements to the GatewayReq object as you would anyt object attributes, i.e.
>>> it.SessionId = 'blahablhabalh'
>>> it
(GatewayReq){
   SessionId = "blahablhabalh"
   # the rest removed for readability

you would then call the redeem method like so :
>>>> client.service.redeem(it)

EDIT
you can create the required types using the below syntax :
entry1 = client.factory.create('ns0:GatewayReq.ns0:VoucherReqDtls')
>>> entry1
(VoucherReqDtls){
   VoucherType = None
   VoucherReq[] = <empty>
 }

This uses the mechanism to access none top level types as specified here suds docs - FACTORY
then you can add this to the main request object as below :
>>> entry1.VoucherType = 'GV'
>>> entry1.VoucherReq.append([12,34,56])
>>> entry1
(VoucherReqDtls){
   VoucherType = "GV"
   VoucherReq[] =

      12,
      34,
      56,
 }
>>> entry1.VoucherReq.append(23)
>>> entry1
    (VoucherReqDtls){
       VoucherType = "GV"
       VoucherReq[] =

      12,
      34,
      56,
      23,
 }

>>> it.VoucherReqDtls.append(entry1)
>>> it
(GatewayReq){
   SessionId = None
   TerminalId = None
   StoreCode = None
   CashMemoNo = None
   CashMemoDate = None
   InvoiceAmount = None
   TimeStamp = None
   CashierId = None
   MerchantId = None
   SPCReqDtls =
      (SPCReqDtls){
         SPCNo = None
         SPCAmt = None
      }
   VoucherReqDtls[] =
      (VoucherReqDtls){
         VoucherType = "GV"
         VoucherReq[] =

            12,
            34,
            56,
            23,
  },
   CardReqDtls =
      (CardReqDtls){
         CardType = None
         CardReq =
            (CardReq){
               CardNo = None
               TransAmt = None
            }
      }
  }

this create xml as below which mathches the required syntax :
<SOAP-ENV:Header/>
   <ns0:Body>
      <ns1:GatewayReq>
         <ns1:SessionId>
            <ns1:SessionId/>
            <ns1:TerminalId/>
            <ns1:StoreCode/>
            <ns1:CashMemoNo/>
            <ns1:CashMemoDate/>
            <ns1:TimeStamp/>
            <ns1:CashierId/>
            <ns1:VoucherReqDtls>
               <ns1:VoucherType>GV</ns1:VoucherType>
               <ns1:VoucherReq>12</ns1:VoucherReq>
               <ns1:VoucherReq>34</ns1:VoucherReq>
               <ns1:VoucherReq>56</ns1:VoucherReq>
               <ns1:VoucherReq>23</ns1:VoucherReq>
            </ns1:VoucherReqDtls>
            <ns1:VoucherReqDtls>
               <ns1:VoucherType>GV</ns1:VoucherType>
               <ns1:VoucherReq>12</ns1:VoucherReq>
               <ns1:VoucherReq>34</ns1:VoucherReq>
               <ns1:VoucherReq>56</ns1:VoucherReq>
               <ns1:VoucherReq>23</ns1:VoucherReq>
            </ns1:VoucherReqDtls>
         </ns1:SessionId>
         <ns1:TerminalId/>
         <ns1:StoreCode/>
         <ns1:CashMemoNo/>
         <ns1:CashMemoDate/>
         <ns1:TimeStamp/>
         <ns1:CashierId/>
      </ns1:GatewayReq>
   </ns0:Body>
</SOAP-ENV:Envelope>

or at least that is how i think it should work
hope it helps


text:
Q: Pandas - how often each string in comma separated rows is present within dataframe I am working with DataFrame containing two columns, one of columns contains comma separated strings, second one contains integers. I want to iterate through column with strings, save each unique string from each row, assign integer value from second column to each string. In other words,
A           B
a,b,c,d     0
a,b,c,d     10
a,b,d,e     89
a,b,d,e     111

In this example:
a = 220, b = 220, c = 10, d = 220, e = 210

I am selecting interesting columns from my csv file,
revcat = DataFrame(data, columns = ['Tag', 'Revenue'])

This gives me ndarray with unique values in 'Tag' and transform it to another DataFrame.
uniqtag = rev1.Tag.str.split(",").apply(pd.Series).stack().unique()
tag_stack = pd.DataFrame(uniqtag)

I am stuck here. How, based on this, do I iterate through original 'Tag' column, using unique strings I found and sum values from 'Revenue' column to each 'Tag'?

A: You could do with Series.str.get_dummies, Series.mul and Series.sum:
df['A'].str.get_dummies(sep=',').mul(df['B'], axis=0).sum()

a    210
b    210
c     10
d    210
e    200

Explanation
df.A.str.get_dummies(sep=',')

This yields a DataFrame that looks like this:
   a  b  c  d  e
0  1  1  1  1  0
1  1  1  1  1  0
2  1  1  0  1  1
3  1  1  0  1  1

Then using .mul with your value column would yield:
     a    b   c    d    e
0    0    0   0    0    0
1   10   10  10   10    0
2   89   89   0   89   89
3  111  111   0  111  111

Which finally, applying .sum along index axis will give you your final output:
a    210
b    210
c     10
d    210
e    200

A: Here are the steps I'd use

*

*Split on "," and use expand=True to get a dataframe back where each letter is in its own column (I'm assuming right now, based on your example, that you always have the same number of splits? Is this true?)

*"Melt" that dataframe so that instead of having multiple columns created from each row in the original df, you have a long dataframe where each row is a letter and its index in the original df.

*Convert from the indices to the values in the B column

*Group by the letter and sum across B.
import pandas as pd

data = [
    ("a,b,c,d", 0),
    ("a,b,c,d", 10),
    ("a,b,d,e", 89),
    ("a,b,d,e", 111),
]
df = pd.DataFrame(data, columns=["A", "B"])

#   A       B
# 0 a,b,c,d 0
# 1 a,b,c,d 10
# 2 a,b,d,e 89
# 3 a,b,d,e 111

melted = df.A.str.split(",", expand=True).reset_index().melt(id_vars="index", value_name="A")
melted["B"] = df.B.loc[melted["index"]].values
melted.groupby("A").B.sum()

# value
# a    210
# b    210
# c    10
# d    210
# e    200

Note - I think you have the sums incorrect in the question; a few of them seem to be off by 10.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Zizaco / entrust throws error with @permission in blade I am using a package Zizaco / entrust for role-base access control (RBAC).
The user role checks in a view with @permission, Like wise,
@permission('role-create')
     Create New Role
@endpermission

which is equal to,
<?php if (\Entrust::can'role-create') : ?>
    <a class="btn btn-success" href="<?php echo route('roles.create'); ?>"> Create New Role
<?php endif; // Entrust::can ?>

But it throws the following error:
Parse error: syntax error, unexpected ''role-create'' (T_CONSTANT_ENCAPSED_STRING) (View: /var/www/rbac/resources/views/roles/index.blade.php)

A: Simply double the small brackets on your permission name that solve my problem

@permission(('role-create'))
     Create New       Role
@endpermission

A: this is a bug with in the package but you can fix it in your project
go to vendors directory there find a entrust directory then from there go to src/Entrusts/EntrustServiceProvider.php
there you find your blade directive code like below
\Blade::directive('permission', function($expression) {
    return "<?php if (\\Entrust::can({$expression}) : ?>";
 });

there you see one starting bracket is missing after can simply add that starting bracket like below
\Blade::directive('permission', function($expression) {
     return "<?php if (\\Entrust::can({$expression})) : ?>";
 });

Or  Use with two parenthesis. Like this:
@permission(('role-edit'))  @endpermission
for further information please check the below link
https://github.com/Zizaco/entrust/issues/657
Note : In prior versions of Laravel, when registering custom Blade directives using the directive method, the $expression passed to your directive callback contained the outer-most parenthesis. In Laravel 5.3, these outer-most parenthesis are not included in the expression passed to your directive callback. Be sure to review the Blade extension documentation and verify your custom Blade directives are still working properly.


text:
Q: Sample Facebook classes for c#? Like some of you allready know, i'm trying to get data from facebook in JSON format and view it in a gridview or something like that.
With some help of StackOverflow, i managed to get the data i needed.
Now I want to make a List of my json string.
Do I have to make a class for every JSON object in my json string? Like the class user, location, work_info, education_info?
Is there any place where i can find the c# class files for all the facebook objects?
I think there are a lot of programers who use these classes, does everyone write the same classes again?
I have added a reference to the facebook(.web) sdk. But I don't know if I can use this for my problem.
I hope you can help me,
Thx!

A: The reason why there are not strongly typed classes for Facebook Schema in the Facebook C# SDK is that they usually change very frecuently. That's why the developers of the Facebook C# SDK decided not to go that way:

*

*http://ntotten.com/2010/08/dynamic-csharp-with-frequently-changing-web-services/

*http://ntotten.com/2010/09/dynamic-objects-and-the-facebook-c-sdk/
Although if read the Roadmap: http://facebooksdk.codeplex.com/wikipage?title=Road%20Map you will see that there are plans for a strongly typed Graph API objects but it looks like there is no much activity in that area.
If you need strongly typed classes for your app, you will probably only use a few that are easy to create.


text:
Q: After i have updated my android studio its showing error like Android resource compilation failed.please help me Android resource compilation failed
Output:  C:\Users\DevoDev1\AndroidStudioProjects\Test\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1339: error: unescaped apostrophe in string
"Who should feed "First Feed" or Anna Prasana to the baby? \n\n (a) Father \n (b) Mother \n (c) Uncle (Mother's Brother) \n (d) Grand Father (Month's father) \n\n Who else can feed first?".
C:\Users\DevoDev1\AndroidStudioProjects\Test\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1339: error: not a valid string.
C:\Users\DevoDev1\AndroidStudioProjects\Test\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1343: error: unescaped apostrophe in string
"Lamp should be facing our side or God\'s side \n\n (a) To God side, because we are offering to God \n (b) Our side, because we need the God's grace on us \n (c) Doesn't matter \n\n What is your take?".
C:\Users\DevoDev1\AndroidStudioProjects\Test\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1343: error: not a valid string.
C:\Users\DevoDev1\AndroidStudioProjects\Test\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1455: error: unescaped apostrophe in string
"Don't loosen your belt".
C:\Users\DevoDev1\AndroidStudioProjects\Test\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1455: error: not a valid string.

Command: C:\Users\DevoDev1.gradle\caches\transforms-1\files-1.1\aapt2-3.2.0-4818971-windows.jar\85067246fdfeb2b4bb965a42850c6b89\aapt2-3.2.0-4818971-windows\aapt2.exe compile --legacy \
        -o \
        C:\Users\DevoDev1\AndroidStudioProjects\Test\app\build\intermediates\res\merged\debug \
        C:\Users\DevoDev1\AndroidStudioProjects\Test\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
Daemon:  AAPT2 aapt2-3.2.0-4818971-windows Daemon #0

A: The errors are in your strings file. Replace this strings
Who should feed "First Feed" or Anna Prasana to the baby? \n\n (a) Father \n (b) Mother \n (c) Uncle (Mother's Brother) \n (d) Grand Father (Month's father) \n\n Who else can feed first?

Lamp should be facing our side or God\'s side \n\n (a) To God side, because we are offering to God \n (b) Our side, because we need the God's grace on us \n (c) Doesn't matter \n\n What is your take?

Don't loosen your belt

With:
Who should feed \"First Feed\" or Anna Prasana to the baby? \n\n (a) Father \n (b) Mother \n (c) Uncle (Mother\'s Brother) \n (d) Grand Father (Month\'s father) \n\n Who else can feed first?

Lamp should be facing our side or God\'s side \n\n (a) To God side, because we are offering to God \n (b) Our side, because we need the God\'s grace on us \n (c) Doesn\'t matter \n\n What is your take?

Don\'t loosen your belt

You missed some apostrophe and some double quotes

A: I had the same problem. Try to open values.xml via Project in android studio
C:\Users\DevoDev1\AndroidStudioProjects\Test\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml

find lines: 1339, 1343, 1455 and edit them.

A: Faced the same problem after updating to 3.3.2. I ignored the current project and fresh clone or create a new project which solved the issue for me.

A: In my case, I had several apostrophes in the strings that were tagged with errors.  Unfortunately, the Android Studio IDE does not red-underline all words with apostrophes if there are several apostrophes in a string, so it is very easy to miss apostrophes.  Look carefully at the error report and double check the strings that are labeled.  You may find that you escaped SOME of the apostrophes in the string, but not all of them


text:
Q: UIScrollView animation laggy I'm writing an reader for iPad that shows images (1024x1322 max) in a UIScrollView
each image is loaded in a background thread when it's needed (during scroll) (there is always 3 images loaded at max).
My problem is: when the data is loaded I'm updating the UIImageView, in my background thread like that:
image= [[UIImage alloc] initWithContentsOfFile: file];
[content setImage:image]

It seems to 'lock' the main thread and make the UISCrollView animation not smooth at all.
Thank you in advance for any clue

A: You should never set the image of an image view (or any property of any UI component for that matter) from a background thread. UIKit is not thread-safe. You need to pass the image to the main thread, using either GCD or performSelectorOnMainThread:withObject:waitUntilDone:.

A: do something like this in your background thread, instead of using UIImage
CGDataProviderRef dataProvider = CGDataProviderCreateWithFilename("file.png");
CGImageRef image = CGImageCreateWithPNGDataProvider(dataProvider, NULL, NO, kCGRenderingIntentDefault);

pass back the image ref to your main thread then create the UIImage with [UIImage imageWithCGImage:image]
Hope this helps


text:
Q: Собрать значения после цикла и просуммировать возник такой вопрос:
У меня есть ввод данных в таком формате:
l = int(input("Задайте количество звеньев: "))

d = [int(i) for i in input("Задайте шаг звеньев: "). split()]

Мне необходимо получить первое и крайнее звено:
l_list = [x for x in range(1, i +1)]
first_and_last_l = [l_list[0], l_list[-1]]

Затем с помощью цикла я выполняю действия для каждого значения списка:
for i in range(len(d)) :
    f = 5 * (6 * d[i])

Затем мне необходимо провести вычисления только для первого и крайнего звена:
 M = (f / 5)

Но в итоге, как и должно быть, в выводе я получаю:
Например l = 5:
2
2
2
2
2

Т.е. пять выводов результата вычисления М
Вопрос, как собрать эти результаты М и просуммировать в один???
Все результаты и выводы условные, важна лишь суть

A: Вопрос, как собрать эти результаты М и просуммировать в один???
что мешает иметь счетчик и каждый раз увеличивать его на M?
или сохранять в массиве и затем вызвать функцию sum()
P.S.
Непонятна в общем задача - вы используете только крайние значения (первый и последний), зачем дальше что-то вычислять для промежуточных (у вас это f)
вы бы более корректно задачу и пример описали (в примере хотя бы переменные назовите одинаково, а то, что за i, что за d?)
P.P.S.
кстати
d = [int(i) for i in input("Задайте шаг звеньев: "). split()]

можно превратить в:
d = list(map(int, input("Задайте шаг звеньев: ").split()))

а
l_list = [x for x in range(1, i +1)]

в
l_list = list(range(1, i + 1))


text:
Q: What is the difference between Servlet response methods addHeader and setHeader? Can I use setHeader to set an new header?
Or Do I need to addHeader first, then use setHeader method?

A: Both setHeader() and addHeader() will add a header and value to the response if the header is not already in the response. The difference between set and add shows up when the header is there. In that case: setHeader() overwrites the existing value, whereas addHeader() adds an additional value.

A: The documentation says that you can add multiple values to a particular header using the addHeader method, whereas an initial value would be overwritten if you use the setHeader method.
In both cases a non-existent header would be created.

A: Javadocs are your friend:
void addHeader(String name, String value)

Adds a response header with the given name and value.
      This method allows response headers to have multiple values.

void setHeader(String name, String value)

Sets a response header with the given name and value. If the header had already been set,
      the new value overwrites the previous one. The containsHeader method can be used to test
      for the presence of a header before setting its value.


text:
Q: UAC pop up red when upgrading installation created with installshield Does anyone know why when upgrading an installation that was created using installshield, the UAC would come up red as shown below.

It only happens when installing an upgrade for a current user installation. Also both the original install and the upgrade have been signed using the same certificate and I have ensured that the certificate and the Root CA are installed.

A: This article implies that the program (strictly speaking the publisher) has been blocked and will need a "run anyway" to start it:
https://blogs.msdn.microsoft.com/oldnewthing/20070330-00/?p=27433/
A Windows Installer major upgrade is a fresh install that will remove the previously installed product if configured that way. It's still a new product that requires elevation. You may be thinking it's the same as UAC patching, but a major upgrade is not a patch, an msp file.


text:
Q: "Uncaught ReferenceError: Template is not defined" (same for Router, Meteor, Mongo) Trying to port Crowducate from Meteor 0.8 to 1.0. I ran "meteor update".
Branch for Meteor 1.0 is --> here.
I had update-issues, i.e. I couldn't remove the "old" iron-router for the "new" iron:router. So currently, both versions are installed (this has to change, of course). Meteor package file:
# Meteor packages used by this project, one per line.
#
# 'meteor add' and 'meteor remove' will edit this file for you,
# but you can also edit it by hand.

# Packages by Meteor
standard-app-packages
preserve-inputs
audit-argument-checks
spiderable
less
coffeescript
accounts-password
accounts-facebook
accounts-google
accounts-ui

# Packages by community
minimongoid
iron-router
iron:router
kaptron:minimongoid

# Packages by Manuel Schoebel

Running meteor: Gives the following error:

In the end, I also get the following error:
Exception in defer callback: TypeError: Cannot read property 'insert' of undefined
at Utils.extend.autoRender (http://localhost:3000/packages/iron-router.js?af9f4791b8af4582a37d93bcade1eed163a976a8:1636:17)
at http://localhost:3000/packages/iron-router.js?af9f4791b8af4582a37d93bcade1eed163a976a8:1465:16
at _.extend.withValue (http://localhost:3000/packages/meteor.js?61916b1060b33931a21f104fbffb67c2f3d493c5:945:17)
at http://localhost:3000/packages/meteor.js?61916b1060b33931a21f104fbffb67c2f3d493c5:430:45
at Object.<anonymous> (http://localhost:3000/packages/meteor.js?61916b1060b33931a21f104fbffb67c2f3d493c5:973:22)
at onGlobalMessage (http://localhost:3000/packages/meteor.js?61916b1060b33931a21f104fbffb67c2f3d493c5:367:23)

So most things are undefined. I also locally changed Meteor.Collection to Mongo.Collection. Now, both are undefined.
Thanks for trying to help out,
Amir
Side note: Always looking for collaborators on this project. Contact me. :)

A: I also had these errors given I had installed Iron Router via meteorite:
$ mrt add iron-router

This installed an older version which is incompatible with Meteor 1.x.
Try removing iron-router via meteorite and installing via meteor:
$ mrt remove iron-router
$ meteor add iron:router

Just to be safe run reset before relaunching:
$ meteor reset
$ meteor

A: I just had the same problem.  I tried following @Jason's instructions but kept getting:
error: unknown package in top-level dependencies: iron-router

when I tried to install iron:router.  Thanks to this thread I finally got the issue resolved by removing iron-router from .meteor/packages.  Apparently mrt remove iron-router doesn't completely remove all traces of iron-router.

A: For template undefined error,
try run meteor reset command and then start server with meteor
Note: meteor reset will do reset your build and also local mongodb data
Update: It should remove the error but anyways try full uninstall of meteor from your system and install it again.
The meteor core installation might get corrupted while auto updating from 0.8 to 1.0 version
Uninstall meteor -
rm -rf ~/.meteor
rm -rf /usr/local/bin/meteor
Install
curl https://install.meteor.com/ | sh
Above will install latest version of meteor i.e 1.0
and after that now update your project with
cd <your-project-directory>
meteor update --release 1.0.0

A: this worked for me:
meteor remove iron-router


text:
Q: Can I use both systemd-networkd and NetworkManager, or is there an GUI/ncurses alternative to Network Manager? I am getting used to netplan.io on my laptop after routinely uninstalling it for several years in favor of ifupdown.
This is probably far-fetched, but since it's running a desktop front-end (plasma), I'm wondering if it'd be possible to use it to use two different renderers simultaneously - one for ethernet, and one for wifi, as I have failed to find a GUI for systemd-networkd, but would still like to be able to configure the wifi with a GUI.
Example:
"network": {
  "version": 2,
  "renderer": "networkd",
  "ethernets": {
    "enp0s31f6": {
      "dhcp4": false,
      "addresses": [
        "192.168.1.28/24"
      ],
      "routes": [
        {
        "to": "default",
        "via": "192.168.1.1"
        }
      ],
      "nameservers": {
        "addresses": [
          "192.168.1.2", "192.168.1.3"
        ],
        "search": [
          "domain.com"
        ]
      },
      "dhcp6": true
    }
  },
  "wifis": {
    "wlan0": {
      "renderer": "NetworkManager"
    }
  }
}

(I've been writing my configs in JSON and converting them with yq, since I like how JSON is a bit more explicit)
If it is impossible to use two renderers at once, is there an alternative to NetworkManager but has a similar interface that uses ncurses or Qt, and will interact with  wlan0 on systemd-networkd?

A: I came across Intel's connman package, which appears to work just fine, and there is a Qt interface package for it called cmst.
I didn't think it would work with systemd-networkd, but it let me join the local wifi network without any issues, and it is in fact controlling the configuration of systemd-networkd, as evidenced by its unit file:
$ sudo systemctl status systemd-networkd
● systemd-networkd.service - Network Configuration
     Loaded: loaded (/lib/systemd/system/systemd-networkd.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2022-01-31 23:04:42 PST; 22h ago
TriggeredBy: ● systemd-networkd.socket
       Docs: man:systemd-networkd.service(8)
   Main PID: 4537 (systemd-network)
     Status: "Processing requests..."
      Tasks: 1 (limit: 23746)
     Memory: 2.0M
        CPU: 5.559s
     CGroup: /system.slice/systemd-networkd.service
             └─4537 /lib/systemd/systemd-networkd

Feb 01 20:49:59 treygouty systemd-networkd[4537]: br-int: Gained carrier
Feb 01 20:50:00 treygouty systemd-networkd[4537]: ovs-system: Gained IPv6LL
Feb 01 20:50:00 treygouty systemd-networkd[4537]: br-int: Gained IPv6LL
Feb 01 20:50:02 treygouty systemd-networkd[4537]: enp0s31f6: Gained carrier
Feb 01 20:50:03 treygouty systemd-networkd[4537]: enp0s31f6: Gained IPv6LL
Feb 01 20:50:04 treygouty systemd-networkd[4537]: enp0s31f6: DHCPv6 address redacted/128 (valid for 4h, preferred for 2h 30min)
Feb 01 20:52:33 treygouty systemd-networkd[4537]: wlan0: Link UP
Feb 01 20:53:57 treygouty systemd-networkd[4537]: wlan0: Connected WiFi access point: happyhut (86:2a:a8:88:b5:21)
Feb 01 20:53:57 treygouty systemd-networkd[4537]: wlan0: Gained carrier
Feb 01 20:53:58 treygouty systemd-networkd[4537]: wlan0: Gained IPv6LL

connman appears to be a decent connection manager in its own right, with a CLI helper named connctl - here's the identification of the technologies, and a sampling of its CLI monitor:
$ for i in state technologies monitor; do connmanctl $i; done
  State = online
  OfflineMode = False
  SessionMode = False
/net/connman/technology/p2p
  Name = P2P
  Type = p2p
  Powered = False
  Connected = False
  Tethering = False
/net/connman/technology/ethernet
  Name = Wired
  Type = ethernet
  Powered = True
  Connected = True
  Tethering = False
/net/connman/technology/wifi
  Name = WiFi
  Type = wifi
  Powered = True
  Connected = True
  Tethering = False
  TetheringIdentifier = redacted
/net/connman/technology/bluetooth
  Name = Bluetooth
  Type = bluetooth
  Powered = False
  Connected = False
  Tethering = False
Manager      ServicesChanged      = {
unchanged                ethernet_c85b763c1a3d_cable
unchanged                ethernet_4e09c1a325ae_cable
unchanged                ethernet_7ab3c8ed895b_cable
unchanged                wifi_e4b318e0de7c_6861707079687574_managed_psk
unchanged                wifi_e4b318e0de7c_7866696e69747977696669_managed_none
unchanged                wifi_e4b318e0de7c_4d4f544f37464441_managed_psk
unchanged                wifi_e4b318e0de7c_4e4554474541523430_managed_psk
}, {
removed                  /net/connman/service/wifi_e4b318e0de7c_466c61707079_managed_psk
removed                  /net/connman/service/wifi_e4b318e0de7c_73616c6f6e333630_managed_psk
removed                  /net/connman/service/wifi_e4b318e0de7c_hidden_managed_ieee8021x
removed                  /net/connman/service/wifi_e4b318e0de7c_536861726a6f77696669_managed_psk
removed                  /net/connman/service/wifi_e4b318e0de7c_hidden_managed_psk
}
Manager      ServicesChanged      = {
unchanged                ethernet_c85b763c1a3d_cable
unchanged                ethernet_4e09c1a325ae_cable
unchanged                ethernet_7ab3c8ed895b_cable
unchanged                wifi_e4b318e0de7c_6861707079687574_managed_psk
}, {
removed                  /net/connman/service/wifi_e4b318e0de7c_4d4f544f37464441_managed_psk
removed                  /net/connman/service/wifi_e4b318e0de7c_7866696e69747977696669_managed_none
removed                  /net/connman/service/wifi_e4b318e0de7c_4e4554474541523430_managed_psk
}

But the GUI was what I was really after.  Despite not looking all that slick, it actually appears to have access to quite a few more features than NetworkManager typically would:

So, there you have it.  Nice to know there's an alternative!

A: Yes, it is possible to use NetworkManager for one set of interfaces and networkd for another.  As documented at https://netplan.io/reference/:
renderer (scalar)
  Use the given networking backend for this definition. Currently
  supported are networkd and NetworkManager. This property can be
  specified globally in network:, for a device type (in e. g.
  ethernets:) or for a particular device definition. Default is
  networkd.

While not explained there, if you have multiple interfaces of each type, it is possible to have a separate file for each renderer and declare the renderer: at the top level within the file so that you don't have to repeat it for each interface.


text:
Q: What are the relationships between twisted.cred.portal.IRealm, Portal and avatar I'm trying to use Twisted's HTTP basic authentication to control access to some protected resources.
According to some articles, it is necessary to use three important concepts: Realm, Portal and avatar. Now I'm wondering if the Realm and avatar is one to one correspondence.
Let's look at an example
import sys

from zope.interface import implements

from twisted.python import log
from twisted.internet import reactor
from twisted.web import server, resource, guard
from twisted.cred.portal import IRealm, Portal
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse

class GuardedResource(resource.Resource):
    """
    A resource which is protected by guard
    and requires authentication in order
    to access.
    """
    def getChild(self, path, request):
        return self

    def render(self, request):
        return "Authorized!"

class SimpleRealm(object):
    """
    A realm which gives out L{GuardedResource} instances for authenticated
    users.
    """
    implements(IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        if resource.IResource in interfaces:
            return resource.IResource, GuardedResource(), lambda: None
        raise NotImplementedError()

def main():
    log.startLogging(sys.stdout)
    checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe='blow')]
    wrapper = guard.HTTPAuthSessionWrapper(
        Portal(SimpleRealm(), checkers),
        [guard.DigestCredentialFactory('md5', 'example.com')])
    reactor.listenTCP(8889, server.Site(
          resource = wrapper))
    reactor.run()

if __name__ == '__main__':
    main()

Of course I know the SimpleRealm is used to return the corresponding resource, e.g. GuardedResource in above example. However, I don't know what to do when there lots of resources to be guarded. For example, I have GuardedResource1, GuardedResource2 and GuardedResource3, maybe they need the same or different number of parameters when they are initialized; If so, is it necessary to implement SimpleRealm1, SimpleRealm2 and SimpleRealm3, respectively?

A: Someone asked this same question on the Twisted mailing list, with very similar code samples - http://twistedmatrix.com/pipermail/twisted-python/2015-December/030042.html - so I'll refer you to my answer there: http://twistedmatrix.com/pipermail/twisted-python/2015-December/030068.html

Rather than thinking of a resource as always existing and just needing to have a lock on it or not, consider the more flexible model (the one that cred actually implements) where a single Avatar object (in this case: the top IResource returned from SimpleRealm) is the top level of "everything the user has access to".  In other words, 'GuardedResource' should have a 'getChild' method which makes the determination if the user they represent (really, at least the avatarId should be supplied to GuardedResource.init) has access to other resources, and return them if so, and appropriate errors if not.
Even the resources available to a not-logged-in user (see twisted.cred.credentials.Anonymous) is just another avatar, the one served up to unauthenticated people.
So, if you have https://myapp.example.com/a/b/secure/c/d https://myapp.example.com/a/b/secure/c/d, https://myapp.example.com/a/b/secure https://myapp.example.com/a/b/secure would be the guarded resource, and then SecureResource.getChild("c", ...) would return "c", which would in turn return "d" if the logged-in user has access to it.

Hopefully this answer worked for you on the list :-).


text:
Q: How can I draw a polygon with a fixed area in ArcMap Is there a way to draw a polygon with a fixed area in ArcMap?  For example, I'm trying to create a 40,000 foot boundary around a feature, but the boundary does not have to be any specific length or width.

A: Calculate a square that meets your perimeter length or area requirement, then create a circle buffer where buffer distance = len/2
Convert the circle to envelope and that will create the square.
In this case your square will be 200 ft on each side

*

*If your features are poly or line geometry then convert features to point

*Create a 100 ft buffer from each feature.

*Input your newly created buffers into the Feature Envelope to Polygon tool


text:
Q: Error: Message content must be a non-empty string. || if (typeof data !== 'string') throw new error(errorMessage); Hi i have problem with using guild on my discord bot. Whenever i want to return the amount of the users on my server i recive this error

if (typeof data !== 'string') throw new error(errorMessage);

RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string.

if (cmd === `name`) { //This is working when used on discord text-channel
        msg.reply(msg.guild.name)
    }
    if (cmd === `users`) {  //This is not working when used on discord text-channel
        msg.reply(msg.guild.memberCount)
    }

A: The memberCount property returns a number which you are trying to send in a channel. The problem is that sending a number is not allowed. Your message content must always be a string.
You can solve this problem by using the String function to send a number. Your command will look like this:
if(cmd === `users`){
    msg.reply(String(msg.guild.memberCount));
}


text:
Q: how to resolve system.nullreference exception when calling web application from console application I have added dll reference of my web application inside console application.
I am trying to call web application functions by creating object of web app inside console app.
But the web application controls all are null, throwing null reference exception.
Can anyone help resolving this issue?
Here is my sample code
I am using RadControls Web Application. there is one Radhtmlchart control.
webapp.aspx
<telerik:Radhtmlchart id=chart1 runat="server"/>

webapp.aspx.cs
I am binding control to datasource.
public void Loadchart()
{
chart1.datasource= getdata();
chart1.databind
}

consoleapp
using webapp;

webapp obj= new webapp();
obj.Loadchart();

while running the console app, I am getting error on Chart1.;object reference not set to instance of object.

A: If I understand your question correctly, I think you should change your approach a little because a console application does not have a GUI. Therefore the web application controls would not be expected to exist.
Using a model/view architecture, move all of your data specific code to a "Model", where "Model" is one or more classes that store and manipulate the data, and have your "View", that is GUI controls, instantiate and use your "Model" classes. Then instantiate only your "Model" classes within your console app.
If you have GUI specific string manipulation code - code that readies strings for the GUI, you should move that into a separate class as well, so that you can call it from both the console and web app.


text:
Q: FFMPEG Concat failing - System cannot find the file specified I'm a PC. I just reversed a video, and want to combine the original file and the reversed file into one new output.mp4 file
I'm using code copied directly from the ffmpeg wiki
ffmpeg -i input1.mp4 -i input2.webm \
-filter_complex "[0:v:0] [0:a:0] [1:v:0] [1:a:0] concat=n=2:v=1:a=1 [v] [a]" \
-map "[v]" -map "[a]" <encoding options> output.mkv

This is my version:
ffmpeg -i C:\xampp\htdocs\reviews\uploads\0115171331.mp4 -i C:\xampp\htdocs\reviews\uploads\R0115171331.mp4 \
-filter_complex "[0:v:0] [0:a:0] [1:v:0] [1:a:0] concat=n=2:v=1:a=1 [v] [a]" \
-map "[v]" -map "[a]"  C:\xampp\htdocs\reviews\output.mp4

And when I run it, it just gives me:

The system cannot find the file specfied.

Again, my other ffmpeg commands worked, and these files (except for output) do exist. I've double checked.
Any idea what could be going wrong?

A: The answer turns out to be that
<encoding options>

is not a literal parameter but user must substitute actual options here.  OP was including it directly causing command to fail.


text:
Q: How the connection is managed by data access application block in Enterprise library? I am new to entlib. I want to know how the connection state is managed by entlib, if I want to create a project which can be accessed by thousands of users is entlib data access application block better to use? Does it manage opening of closing of connections by itself?
Please explain me in detail...

A: I'm afraid this is not really the place for detail, however there is a free ebook called "Developer's guide to Microsoft Enterprise Library 5" which has plenty of detail. If you need more you can also download and examine the code for the whole library.
The main advantage of enterprise library is that it's easy to use, and does a lot of things you would otherwise have to re-implement in your code. Enterprise Library is part of Patterns and practices section in MSDN and implements well thought out and reviewed methods of carrying out common tasks.
Enterprise library helps to resolve ADO.NET issues, such as deciding how your code should call the close method, by automatically managing connections as far as reasonably possible.


text:
Q: How many knights are there?
I cannot deduce the solution. I cannot deduce a solution.
Consider the case in which Anne is a Knave.
If Anne answers "Yes", then they are not both knights. Berne might be a knight, or they might be a knave. If Anne answers "No", then they are both knights. But Anne is a knave, so this leads to a contradiction. Therefore if Anne is a Knave, she answers "Yes", and Berne is either a Knight or Knave.
Consider the case in which Anne is a Knight.
"Yes" indicates they're both knights.
"No" indicates that Berne is a "Knave".
An answer of "No" thus indicates one knight.
An answer of Yes indicates 2 Knights, 1 Knight, or 0 Knights.
This question can only be solved if Anne answered "No".
But we are not given Anne's answer.
As such we cannot discriminate between the options.

A:
Consider the case in which Anne is a Knave. If Anne answers "Yes", then they are not both knights.

Anne is lying, so it could be that either Bernie is a knight and she is a knave or they are both knaves.

If Anne answers "No", then they are both knights. But Anne is a knave, so this leads to a contradiction.

Yup, so that will never happen. So if she responds "No" she is a knight and Bernie is a knave.
In essence, if she responds yes there is no way to tell how many there are. Thus, she responded "No". So there is 1 kinght and 1 knave.


text:
Q: Can't able to pass user information from website to chatbot using directline in microsoft bot framework with python sdk I'm trying to pass user name from website to chatbot using directline feature. I'm using python sdk and following the below link.
https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/04.api/a.welcome-event
my js file looks like
(async function() {
    var myHeaders = new Headers();
    myHeaders.append("Authorization", "Bearer <token here>");
    myHeaders.append("Content-Type", "application/json");
    var raw = JSON.stringify({
      "user": {
        "id": "dl_123"
      },
      "trustedOrigins": []
    });
    var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: raw,
      redirect: 'follow'
    };
    fetch("https://directline.botframework.com/v3/directline/tokens/generate", requestOptions)
      .then(response => response.text())
      .then(result => {console.log(result)

      var  token  = JSON.parse(result).token

        console.log("token",token)

    const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
      if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
        dispatch({
          type: 'WEB_CHAT/SEND_EVENT',
          payload: {
            name: 'webchat/join',
            value: "user_name_here"
          }
        });
      }

      return next(action);
    });

    window.WebChat.renderWebChat(
      {
        directLine: window.WebChat.createDirectLine({ token }),
        store
      },
      document.getElementById('webchat')
    );

    document.querySelector('#webchat > *').focus();
})})().catch(err => console.error(err));

and my python code looks like
if turn_context.activity.name != "webchat/join":
   response = MessageFactory.text(f"Hai {turn_context.activity.value} Welcome to Portal")

but it show none in the place of turn_context.activity.value
I actually want to print username passed from js file here. how to do that.


text:
Q: Reading and writing a vector of classes I have an inheritance hierarchy with three/four levels. And within each level will hold at least one or more classes with different attributes that make that object of a class unique (and of course, inheriting attributes from the level above).
Each object of a class may have different attributes to another therefore my question is, how can I read and write each object to a file and differentiate the attributes?
I do apologise if I have not worded this very well but will be very appreciative if you can help.

A: The problem being horribly underspecified, I'm just going to suggest using a library.
I'm personally quite fond of Boost Serialization for

*

*feature set (object tracking, smart pointers, alias detection, cyclic graphs, polymorphic types and collections)

*non-intrusiveness (you can add serializability to 3rdparty types)

*portability (with the caveat that you should not expect the standard binary archive to be portable across machines/version: use EOS Portable Archives for that

See the sample (which has polymorphic collections): http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#examples
There are more fish in the sea: protobuf is supposedly quite awesome.
You /can/ roll your own using Spirit Qi/Karma, though I'd not suggest this unless you want human readable formats


text:
Q: Time efficiency python class Vs extension type in C I am looking to create a custom scalar type that has magnitude and a bunch of sign bits. I have defined operations such as arithmetic and comparison. I want to use this scalar type with numpy extensively. (Eg., Normal operations would involve multiplying matrices of size 1000 X 1000 multiple times). So I need this to be as efficient as possible. I have an implementation in C++ using Eigen as matrix library but I need a python port to make it easily accessible in python.
I see three ways as of now :

*

*Create a python class

*Create an extension type as explained here

*Using Boost.python and expose my C++ class
The operations of my type are only bit level (addition, for) but they would be done millions of times.
I would like to know what method would create the most efficient scalar type.

*

*writing a class in python Vs using boost, would there be any observable difference in speed

*writing an extension type in C Vs class in python, would the difference be noticable.

I could carry out experiment but I am looking for some experience. If this doesn't get answered, I will answer myself.
Edit:
As suggested by @Parfait, it looks like the best way would be using Cython cdef. Here is a quick benchmark involving numpy and Cython.


text:
Q: Force www subdomain in lighttpd and preserve path I would like to setup my lighttpd powered website to redirect users to the www subdomain when browsing the site without the subdomain. I would also like it to preserve the trailing URL and serve the redirect as a permanent 301 redirect. What sort of rules would I need to throw into my lighttpd.conf file?
example.com -> www.example.com
example.com/pagename -> www.example.com/pagename

A: This will redirect all requests on example.com to www.example.com while preserving the original path:
$HTTP["host"] =~ "^example\.com$" {
  url.redirect = ( "^/(.*)" => "http://www.example.com/$1" )
}


text:
Q: Symfony2 remove default Form fields style class When rendering a form field It adds a class that messes up my styling.. All I want to do is remove the class when rendereing the field, but how can I do that? I know that you can set up classes for fields, but I need to remove a default class.
I render like this:
{{ form_widget(form.plainPassword }}

The only way I can do this now, is go to the vendor bootstrap_3_horizontal_layout file and remove the line:
{% block form_group_class -%}
    col-sm-10 ///remove this
{%- endblock form_group_class %}

However that is not the solution, because you cant manually edit vendor files.. What are my options? How to achieve what I need?

A: You can either define your own theme for a form type or add the html manually and use the raw form variables

A: You should check the documentation about form theme "Application-wide Customizations".
You can create a form theme template which extends bootstrap_3_horizontal_layout and override form_group_class block like this:
{% use 'bootstrap_3_horizontal_layout.html.twig' %}

{% block form_group_class %}{% endblock form_group_class %}

and then set this template as a global form theme in you config.yml (assuming it is located in your MyAppBundle in form/my_form_theme.html.twig):
twig:
    form_themes:
        - 'MyAppBundle:form:my_form_theme.html.twig'


text:
Q: How to highlight a state inside algorithm in beamer? I want to put a box to highlight a state from an algorithm inside beamer frame. For example, the state shown below. How can I draw a such highlight box around it?
\documentclass[xcolor=table,10pt,aspectratio=169]{beamer}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[american]{babel}
\usepackage{amsmath,amssymb,amsthm}
\usepackage[noend]{algpseudocode}

\begin{document}

\begin{frame}{Test}
\begin{algorithmic}
\Procedure{Test}{$a, b$}
    \State $a + b$
\EndProcedure
\end{algorithmic}
\end{frame}

\end{document}

A: The hf-tikz package provides an easy way to highlight (parts of) a formula:
\documentclass[xcolor=table,10pt,aspectratio=169]{beamer}

%\usepackage[T1]{fontenc}
%\usepackage[utf8]{inputenc}
\usepackage[american]{babel}
%\usepackage{amsmath,amssymb,amsthm}
\usepackage[noend]{algpseudocode}

\usepackage[beamer]{hf-tikz}

\begin{document}

\begin{frame}
\frametitle{Test}
\begin{algorithmic}
\Procedure{Test}{$a, b$}
    \State $\tikzmarkin<2>{a}a + b\tikzmarkend{a}$
\EndProcedure
\end{algorithmic}
\end{frame}

\end{document}

A: May I suggest an alternative? Make use of beamer's \alert:

\documentclass{beamer}

\usepackage[noend]{algpseudocode}

\begin{document}

\begin{frame}{Test}
  \begin{algorithmic}
  \Procedure{Test}{$a, b$}
    \State \alert<2>{$a + b$}
  \EndProcedure
  \end{algorithmic}
\end{frame}

\end{document}


text:
Q: synthesis of dynamic mux on std_logic_vector bytes I have a FIFO who's size is determined according to a parameter in the package:
signal fifo : std_logic_vector(FIFO_SIZE*8 -1 downto 0);
I also have a 4 bit vector (numOfBytes) saying how many bytes are in the FIFO at any given time (up to 8).
I want the data out (a single byte) from the FIFO to be determined according the numOfBytes signal:
Do <= fifo(to_integer(unsigned(numOfBytes)*8 -1 downto to_integer(unsigned(numOfBytes)*8 -8) when numOfBytes /= x"0" else (others => '0');
when simulating, this works well, however when I try to synthesis it (using Synopsys DC) I get an elaboration error upon linking the design saying "Constant value required (ELAB-922)".
The ELAB code means "This error message occurs because an expression in the indicated line of your RTL description does not evaluate to a constant value, as required by the language."
How else can I make the output mux so it will undergo synthesis?
if not for the parameter i'd change the Do line to a regular mux, but it can't work with the parameters. (I can't call fifo(63 downto 54) when fifo is 4 byte...)
p.s.
I tried working with conv_integer in the beginning, but changed to to_integer(unsigned())due to answers found on the web.

A: Signal indexes used to construct a range have to be compile-time constants for synthesis to accept them.
There are two ways to solve this problem:
1) Change your FIFO to use an array. This is the standard way of declaring any form of memory, such as a FIFO.
type fifo_type is array(0 to FIFO_SIZE-1) of std_logic_vector(8-1 downto 0);
signal fifo : fifo_type;
...
Do <= fifo(to_integer(unsigned(numOfBytes))-1) when(numOfBytes/=0) else (others=>'0');

2) Use a loop to convert the variable into a constant. This is a common way to code a generic mux.
Do <= (others=>'0');
for i in 0 to FIFO_SIZE-1 loop
    if(numOfBytes=i+1) then
        Do <= fifo((i+1)*8-1 downto i*8);
    end if;
end loop;

I would recommend the first approach for larger, memory-based FIFOs, and the second for smaller, register-based ones.

A: If the FIFO created with a number of bytes, instead of combining it into the same std_logic_vector then Synopsys DC may be able to handle it.  Code could look like:
library ieee;
use ieee.numeric_std.all;

architecture syn of mdl is

  ... Declaration of FIFO_SIZE natural constant

  type fifo_t is array(natural range <>) of std_logic_vector(7 downto 0);
  signal fifo : fifo_t(FIFO_SIZE - 1 downto 0);

begin

  ... Handling FIFO insert and remove

  Do <= fifo(to_integer(unsigned(numOfBytes))) when numOfBytes /= x"0" else (others => '0');

end architecture;

A: If you don't need a runtime-dynamic size to the FIFO, use a generic on your entity.
If you truly need a dynamic sized FIFO, you'll have to use a loop in a process as someone else said.  But be very careful how you use such a FIFO, as if you change the size of it while someone is reading or writing, bad things may happen!


text:
Q: Gradle user home not working in gradle.properties file I don't want to set environment variables,
So I defined gradle.user.home in the global $USER_HOME/.gradle/gradle.properties file,
but it didn't work.
Windows 10
JDK 1.8
Gradle 4.10.3
IntelliJ IDEA 2017.3.6
Here is my gradle.properties:
systemProp.gradle.user.home=E:\\dev\\repository\\.gradle
# OR
gradle.user.home=E:\\dev\\repository\\.gradle


text:
Q: Programming NAND with generated UBI binary Our system generates a UBI partition that is being created in NAND on first boot. The system is able to read and write files there. I'm trying to create a binary file that we can use for a NAND 'gang' programmer, so that we can pre-program that partition with some files.
I create a folder/fire structure and use the following two commands:
mkfs.ubifs -r ./files -m 2048 -e 126976 -c 2047 -o ubifs.img
ubinize -o ubi.img -m 2048 -p 128KiB -s 2048 ubinize.cfg

ubinize.cfg:
[files]
mode=ubi
vol_id=0
vol_type=dynamic
vol_name=fs
vol_flags=autoresize
image=ubifs.img

To test my file, using uboot, I program ubi.img at the right offset and boot the system. The system finds the new UBIFS partition which contains valid files! Yay!
The problem: When I change anything in the partition, touch a new file even, and reboot, the partition fails to mount claiming a huge amount of ecc errors:
http://i.imgur.com/qoTr4ag.png
$ log | grep UBI
05:00:59 PM  [    INFO] [        kernel] UBIFS: background thread "ubifs_bgt1_0" started, PID 306
05:00:59 PM  [ WARNING] [        kernel] UBI warning: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 3:4096,
05:00:59 PM  [ WARNING] [        kernel] UBI warning: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 3:4096,
05:01:00 PM  [ WARNING] [        kernel] UBI warning: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 3:4096,
05:01:00 PM  [   ERROR] [        kernel] UBI error: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 3:4096,
05:01:00 PM  [   ERROR] [        kernel] UBIFS error (pid 304): ubifs_scan: bad node
05:01:00 PM  [ WARNING] [        kernel] UBI warning: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 3:4096,
05:01:00 PM  [ WARNING] [        kernel] UBI warning: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 3:4096,
05:01:01 PM  [ WARNING] [        kernel] UBI warning: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 3:4096,
05:01:01 PM  [   ERROR] [        kernel] UBI error: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 3:4096,
05:01:01 PM  [ WARNING] [        kernel] UBI warning: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 4:4096,
05:01:01 PM  [ WARNING] [        kernel] UBI warning: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 4:4096,
05:01:01 PM  [ WARNING] [        kernel] UBI warning: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 4:4096,
05:01:02 PM  [   ERROR] [        kernel] UBI error: ubi_io_read: error -74 (ECC error) while reading 126976 bytes from PEB 4:4096,
05:00:00 PM  [   ERROR] [        kernel] UBIFS error (pid 304): ubifs_recover_master_node: failed to recover master node
05:00:00 PM  [   ERROR] [        kernel] UBIFS error (pid 304): ubifs_recover_master_node: dumping first master node
05:00:00 PM  [    INFO] [        kernel] UBIFS: background thread "ubifs_bgt1_0" stops

Any ideas where I messed up creating my ubi image?

A: RTFM! The -F parameter fixed the errors I listed above.
http://www.linux-mtd.infradead.org/faq/ubifs.html#L_free_space_fixup
In addition, the ubi_reader tools has been a great help in understanding various parameters that go into mkfs and ubinize.
https://github.com/jrspruitt/ubi_reader


text:
Q: Can anybody please assist with syntax in a function in postgresql (from mysql) I am trying to create the following function in PostgreSQL but get the following error. This is from a MySQL procedure that I need to convert to PostgreSQL. I am failing to convert the syntax to PostgreSQL. I am a beginner in PostgreSQL. Please assist me.
CREATE OR REPLACE FUNCTION public.usp_failed_analyze4()
RETURNS TABLE(status varchar) as
$BODY$
    SET @maxdate = (SELECT MAX(analyzetime) FROM  wp_analyze_history);
    SET @maxdateint = (SELECT DATEDIFF(NOW() ,MAX(analyzetime)) FROM  wp_analyze_history);
    SET @STATUS = SELECT Status from wp_analyze_history WHERE Status NOT IN ('OK','Table is already up to date','The Analyze task DID NOT run!') AND  analyzetime = @maxdate);
    SET @STATUSNOTRUN = 'The Analyze task DID NOT run!';
    IF @maxdateint > 7
    THEN SELECT @STATUSNOTRUN;
    ELSE SELECT @STATUS as "";
$BODY$
    LANGUAGE sql;

error: ERROR: syntax error at or near "@"
Position: 109

A: It's hard to tell what you want as you tried to copy the MySQL 1:1.
However, there are several problems in your code:

*

*language sql does not have variables or IF statements. You need to use PL/pgSQL (language plpgsql)

*PL/pgSQL requires a declare block to declare all variables and the actual code needs a begin ... end; block as well.

*You can use SET for assignment

*To store the result of a single row query in a variable use select ... into ... from

*The character @ is invalid in an SQL identifier and can't be used for variable names (which follow the rules of SQL identifiers). In Postgres it's a common habit to prefix variable with something to avoid ambiguity with column names. I use l_ for local variables (but that's completely a personal preference)

*You don't seem to want to return multiple rows, but a single value. So you don't need returns table

*To return something from a function, use return not select
Putting that all together it should look something like this:
CREATE OR REPLACE FUNCTION usp_failed_analyze4()
  RETURNS varchar -- return a single value
AS
$BODY$
declare
  l_maxdate timestamp;
  l_maxdatediff interval;
  l_status text;
  l_statusnotrun text;
begin
    select MAX(analyzetime), current_timestamp - MAX(analyzetime)
      into l_maxdate, l_maxdatediff
    FROM  wp_analyze_history;

    SELECT Status
      into l_status
    from wp_analyze_history
    WHERE Status NOT IN ('OK','Table is already up to date','The Analyze task DID NOT run!')
      AND analyzetime = l_maxdate;

    l_statusnotrun := 'The Analyze task DID NOT run!';
    IF l_maxdatediff > interval '7 days'
    THEN
      return l_statusnotrun;
    ELSE
      return ''; -- strings are enclosed in single quotes in SQL
    end if;
end;
$BODY$
LANGUAGE plpgsql;

There is still room for a lot of optimization, but this matches your initial code as much as possible.


text:
Q: Instagram web/desktop inspired search box If you visit someone's instagram page on desktop/pc, the search bar, when clicked, floats left and then text  can be entered to search. When there is no text in the search field, the search icon and the "search" placeholder go back to the original center position.
I assume javacript/jquery is used to this and I want to implement it as well, but I don't know any script that will be able to accomplish this. Below is my HTML and CSS code, any help will be greatly appreciated!
HTML

    <input type="search" id="search" placeholder="Search" />

CSS
.box{
  margin: 3px auto;

  width: 200px;
  height: 20px;
  padding-right: 10px;
}

.container-1{
  width: 200px;
  vertical-align: middle;
  white-space: nowrap;
  position: relative;

}

.container-1 input#search{
  width: 200px;
  height: 30px;
  background: #FFFFFF;
  border: 1px solid #C5C4C4;
  font-size: 10pt;
  text-align: center;
  color: #000000;

  -webkit-border-radius: 25px;
  -moz-border-radius: 25px;
   border-radius: 25px;

  -webkit-transition: background .55s ease;
  -moz-transition: background .55s ease;
  -ms-transition: background .55s ease;
  -o-transition: background .55s ease;
   transition: background .55s ease;
}

.container-1 input#search::-webkit-input-placeholder {
   color: #A8A7A7;
   letter-spacing: 1px;
   font-size: 12px;
}

.container-1 input#search:-moz-placeholder { /* Firefox 18- */
   color: #A8A7A7;
   letter-spacing: 1px;
   font-size: 12px;
}

.container-1 input#search::-moz-placeholder {  /* Firefox 19+ */
   color: #A8A7A7;
   letter-spacing: 1px;
   font-size: 12px;
}

.container-1 input#search:-ms-input-placeholder {
   color: #A8A7A7;
   letter-spacing: 1px;
   font-size: 12px;
}

input:focus::-webkit-input-placeholder { color:transparent; }
input:focus:-moz-placeholder { color:transparent; } /* Firefox 18- */
input:focus::-moz-placeholder { color:transparent; } /* Firefox 19+ */
input:focus:-ms-input-placeholder { color:transparent; } /* oldIE ;) */

.container-1 .icon{
  position: absolute;
  padding-top: 8px;
  padding-left: 50px;
  font-size: 12px;
  z-index: 1;
  color: #A8A7A7;

}

.container-1 input#search:hover, .container-1 input#search:focus, .container-1 input#search:active{
    outline:none;
    background: #ffffff;

  }

  input::-webkit-search-decoration,
input::-webkit-search-cancel-button {
  display: none;
}

  @media all and (max-width : 370px) {

.box{
  margin: 15px auto;

  width: 200px;
  height: 20px;
  padding-right: 10px;
}
  }

A: I created a simple fiddle to give you a sample look how it can be done. For now i don't know how to make placeholder to be centered so it's with fixed padding.

input {
  width: 200px;
  padding-left: 80px;
  box-sizing: border-box;

  background: url(https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_search_48px-128.png);
  background-size: 16px;
  background-repeat: no-repeat;
  background-position: 62px 0;
}
input:focus {
  padding-left: 16px;
  background-position: 0;
}
<input type="text" placeholder="Search" />

P.S. You can easily animate this effect by providing transition, for example:
transition: all 0.05s ease-in-out;

It should look like that:

input {
  width: 200px;
  padding-left: 80px;
  box-sizing: border-box;

  background: url(https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_search_48px-128.png);
  background-size: 16px;
  background-repeat: no-repeat;
  background-position: 62px 0;

  transition: all 0.05s ease-in-out;
}
input:focus {
  padding-left: 16px;
  background-position: 0;
}
<input type="text" placeholder="Search" />

(search icon from www.iconfinder.com)

A: I implemented a lame simulation of what you asked. Hope it helps.
Instagram is using an Html block similar to this one:

$("#LabelContainer").click(function() {
  $("#Search-Input").show();
  $("#Search-Input").focus();
  $("#LabelContainer").hide();
});

$('body').click(function(evt){
  if (evt.target.id === "LabelContainer" ||
     evt.target.id === "Search-Input")
      return;
  var labelText = $("#Search-Input").val() === '' ? 'Search' : $("#Search-Input").val();
  $("#LabelContainer").text(labelText);
  $("#LabelContainer").show();
  $("#Search-Input").hide();

});
body{
   width 100%;
   height: 100%;
   min-height: 200px;
}

.MainContainer {
    margin: 0 auto;
    height: 30px;
    width: 200px
}

#Search-Input {
    display: none;
    border: solid 1px #dbdbdb;
    border-radius: 3px;
    color: #262626;
    font-size: 14px;
    outline: none;
    padding: 3px 10px 3px 26px;
    z-index: 2;
    box-sizing: border-box;
    height: 100%;
    width: 100%;
}

#LabelContainer {
    border: solid 1px #dbdbdb;
    border-radius: 3px;
    color: #262626;
    font-size: 18px;
    font-weight: bold;
    outline: none;
    padding: 3px 0;
    z-index: 2;
    box-sizing: border-box;
    height: 100%;
    width: 100%;
    text-align: center;
}

.LabelText {

}

        <input id="Search-Input" type="text" placeholder="Search..." value="">

Search


text:
Q: Getting the latest value from a group in pandas I have a dataframe with following structure
Debtor ID    | AccountRating    | AccountRatingDate   | AmountOutstanding    |AmountPastDue
John Snow      Closed             2017-03-01            0                     0
John Snow      Delayed            2017-04-22            2000                  500
John Snow      Closed             2017-05-23            0                     0
John Snow      Delayed            2017-07-15            6000                  300
Sarah Parker   Closed             2017-02-01            0                     0
Edward Hall    Closed             2017-05-01            0                     0
Douglas Core   Delayed            2017-01-01            1000                  200
Douglas Core   Delayed            2017-06-01            1000                  400

What I want to achieve is
Debtor ID    | Incidents of delay    | TheMostRecentOutstanding    | TheMostRecentPastDue
John Snow      2                       6000                          300
Sarah Parker   0                       0                             0
Edward Hall    0                       0                             0
Douglas Core   2                       1000                          400

Counting incidents of delay is pretty straightforward
df_account["pastDuebool"] = df_account['amtPastDue'] > 0
new_df = pd.DataFrame(index = df_account.groupby("Debtor ID").groups.keys())
new_df['Incidents of delay'] = df_account.groupby("Debtor ID")["pastDuebool"].sum()

I am struggling with extracting the most recent amonts outstanding and pastdue. My code is like this
new_df["TheMostRecentOutstanding"] = df_account.loc[df_account[df_account["AccountRating"]=='Delayed'].groupby('Debtor ID')["AccountRatingDate"].idxmax(),"AmountOutstanding"]
new_df["TheMostRecentPastDue"] = df_account.loc[df_account[df_account["AccountRating"]=='Delayed'].groupby('Debtor ID')["AccountRatingDate"].idxmax(),"AmountPastDue"]

But they return Series with all NaN values. Please help me, what am I doing wrong here?

A: You can try this:
df.sort_values('AccountRatingDate')\
  .query('AccountRating == "Delayed"')\
  .groupby('Debtor ID')[['AccountRating','AmountOutstanding','AmountPastDue']]\
  .agg({'AccountRating':'count',
        'AmountOutstanding':'last',
        'AmountPastDue':'last'})\
  .reindex(df['Debtor ID'].unique(), fill_value=0)\
  .reset_index()

Output:
      Debtor ID  AccountRating  AmountOutstanding  AmountPastDue
0     John Snow              2               6000            300
1  Sarah Parker              0                  0              0
2   Edward Hall              0                  0              0
3  Douglas Core              2               1000            400

Details:

*

*First sort dataframe by AccountRatingDate to get the last date as the
last record.

*Filter the dataframe to only those with AccountRatings equal to
'Delayed'

*Groupby Debtor ID with columns to aggregate, then use agg    with a
dictionary to indicate how to aggregate each column

*Reindex with the unique values of Debtor ID to fill zero for those
without any delays

*And, reset index.

And, you can do column renaming with rename and a dictionary:
df.sort_values('AccountRatingDate')\
  .query('AccountRating == "Delayed"')\
  .groupby('Debtor ID')[['AccountRating','AmountOutstanding','AmountPastDue']]\
  .agg({'AccountRating':'count',
        'AmountOutstanding':'last',
        'AmountPastDue':'last'})\
  .reindex(df['Debtor ID'].unique(), fill_value=0)\
  .rename(columns={'AccoutRating':'Incidents of delay',
                   'AmountOutstanding':'TheMostRecentOutstanding',
                   'AmountPastDue':'TheMostRecentPastDue'})\
  .reset_index()

Output:
      Debtor ID  AccountRating  TheMostRecentOutstanding  TheMostRecentPastDue
0     John Snow              2                      6000                   300
1  Sarah Parker              0                         0                     0
2   Edward Hall              0                         0                     0
3  Douglas Core              2                      1000                   400

A: This will sort the values by date (keeping the last value), sum your boolean 'True' values, and then drop duplicates in the index. It will then get rid of the columns you don't want and give you your 'new_df':
df = pd.read_table('fun.txt')
df['pastDuebool'] = df['AmountPastDue'] > 0

df = df.set_index('DebtorID').sort_values('AccountRatingDate')
df['Incidents of Delay'] = df.groupby('DebtorID')['pastDuebool'].sum()
df = df[~df.index.duplicated(keep='last')]

df = df.drop(['pastDuebool', 'AccountRatingDate', 'AccountRating'], axis=1)
new_df = df.rename(columns={'AmountOutstanding':'TheMostRecentOutstanding',
                            'AmountPastDue':'TheMostRecentPastDue'})

print(new_df)

output:
                 AmountOutstanding  AmountPastDue  Incidents of Delay
DebtorID
SarahParker                  0              0                 0.0
EdwardHall                   0              0                 0.0
DouglasCore               1000            400                 2.0
JohnSnow                  6000            300                 2.0


text:
Q: How to make an IF Statement in SSIS How can I create a condition in SSIS like below?
I know how to create it just in SQL Server
Example:
IIF(LEFT(MAT,1) = '"', NULL,  REPLACE(MAT,'""',''))

A: «boolean_expression» ? «when_true» : «when_false»
LEN([Mobile]) == 9 ? ("0" +  [Mobile]) :  [Mobile]

A: SET MAT = LEFT(MAT,1) == '"' ? NULL : REPLACE(MAT,'""','');
IFF statement works condition-based assignment
The IIF() statement has the following format:
=IIF( Expression to evaluate,
         what-to-do when the expression is true,
         what-to-do when the expression is false )

*

*Parameter1: It should be a Boolean Expression.

*Paremeter2: This    value will return when Expression is true.

*Paremeter3: This value    will return when Expression is false.

A: The syntax in SSIS is like this: [condition] : [value if true] ? [value if false] With that said, you could do...
(MAT,1)='' : NULL ? REPLACE(MAT,'""',''))


text:
Q: How to deploy ubuntu container to Azure Container Instance and keep it running I cannot manage to deploy 'ubuntu' to Azure Container instance without it becoming "Terminated" right after the deployment. I tried setting the command to ["/bin/bash"], however, it doesn't stop the container from terminating.

A: It's a common issue you can see. The docker image ubuntu just provides the base container, but no application runs in it to make the Container Instance in the running state. So you need to add the command in the command line to make the container instance in the running state. For example, add the command tail -f /dev/null.
When you do it in the portal, it should look like this:

It just keeps the container in the running state and does not output anything. So there are no logs output.


text:
Q: Does x approach some finite value according to this differential equation? So this question was on a midterm that I wrote recently and I couldn't figure out the answer. We were given the differential equation
$$\frac{dy}{dx} = x^2 + y^2$$
The question asked: As $y \rightarrow \infty$, does $x$ approach some finite value $x_0$?
Also, we were told to think about it intuitively and without solving the eqution. We have not learned how to solve this sort of equation yet.
I thought about it afterwards and this is the answer I got...
Attempt
The equation of the slope of function y is dependent on both the value of y and the value of x. It is in the form of an equation of a circle.
If $x$ approached some value $x_0$ as $y \rightarrow \infty$, then the slope would gradually approach infinity as $y$ got larger and larger. However, since this is an equation of a circle, the value of the slope is bound by the circle, meaning that it can't approach infinity. Therefore, $x$ does not approach some value $x_0$, and we get that $x \rightarrow \infty$.
Is that correct?

A: I don't think this is the case. The value of the slope isn't bound by the circle - it's saying that the value of the slope is ONLY proportional to the distance away from the origin. That is, on every point on the circle $x^2 + y^2 = r^2$, the slope is $r^2$.
From this picture, you see that as the distance from the origin increases, the slope increases more and more rapidly. So this makes it seem that there ought to be an asymptote.


text:
Q: Making my existing RoR controller embeddable I'm trying to figure out the best way to make it possible for external sites to embed parts of my Ruby on Rails app into their website through an iframe. My app allows people to buy tickets to events and we want to allow event organisers to embed the whole ticket buying process into their site.
I've found a couple of answers that have helped with the exact 'how to'
https://www.quora.com/How-do-I-create-a-embeddable-widget-in-rails
Allow users to embed my content into their sites (like blogs) -- rails 4
But my question is more about the best way to actually implement this. We already allow ticket buyers to purchase tickets through our site so I don't particularly want to create a new controller(s) as a lot of what happens in the controller will be the same. On the other hand, we may want to do different redirects for embedded users - I know we can do this with variants but I feel slightly like the embedded user flow will be so different it might just be a bit confusing. What is going to be my most maintainable option?
I'm also keen to avoid duplicating views and given that I believe it's best to inline CSS does anyone have any advice on how to handle this. If I were to render the embedded views through some engine that can inline all the CSS (I believe some email gems do this), is this a good idea and if so can anyone recommend any gems?


text:
Q: Logstash - not able to get the @timestamp to work Logstash noob here, I am trying to get these log lines filtered through logstash.
2015-03-31 02:53:39 INFO  This is info message 5

The config file that I am using is this:
input {
  file {
    path => "/sample/log4j_log.log"
    start_position => beginning
  }
}

filter {
  grok {
    match => [ "message" , "%{DATESTAMP:logtimestamp} %{LOGLEVEL:level} %{GREEDYDATA:msg}" ]
  }

  date {
    locale => "en"
    match => [ "logtimestamp" , "yyyy-MM-dd HH:mm:ss" ]
  }
}

output {
  #elasticsearch { host => localhost }
  stdout { codec => rubydebug }
}

The output I get is
         "message" => "2015-03-31 02:53:39 INFO  This is info message 5",
        "@version" => "1",
      "@timestamp" => "0015-03-30T21:00:11.000Z",
            "host" => "abc",
            "path" => "/sample/log4j_log.log",
    "logtimestamp" => "15-03-31 02:53:39",
           "level" => "INFO",
             "msg" => " This is info message 5"

I see that the logtimestamp field is showing the format as "YY-MM-dd HH:mm:ss", I am not sure why it is getting converted tot his format, and I even tried that in the date filter.
IN those cases I get this output.
{
         "message" => "2015-03-31 02:53:39 INFO  This is info message 5",
        "@version" => "1",
      "@timestamp" => "2015-04-07T17:55:51.231Z",
            "host" => "abc",
            "path" => "/sample/log4j_log.log",
    "logtimestamp" => "15-03-31 02:53:39",
           "level" => "INFO",
             "msg" => " This is info message 5"
}

In all of this the @timestamp is not matching up with the actual log event timestamp and this causes problems for elastic search + kibana visualization.
I have tried to include target => "@timestamp", locale => "en" as suggested by other questions on StackOverflow with no success.
The only thing I seem to not have tried is :
Logstash date parsing as timestamp using the date filter
Which i dont believe is fully applicable to my log event.

A: You grok pattern is incorrect.
Please change to this, Use TIMESTAMP_ISO8601 instead of DATESTAMP
grok {
    match => [ "message" , "%{TIMESTAMP_ISO8601:logtimestamp} %{LOGLEVEL:level} %{GREEDYDATA:msg}" ]
}

Here is the output:
{
     "message" => "2015-03-31 02:53:39 INFO  This is info message 5",
    "@version" => "1",
  "@timestamp" => "2015-03-30T18:53:39.000Z",
        "host" => "BEN_LIM",
"logtimestamp" => "2015-03-31 02:53:39",
       "level" => "INFO",
         "msg" => " This is info message 5"
}


text:
Q: Connectedness in Directed Graphs Suppose $G$ is a directed graph on $n$ vertices where all in-degrees and our-degrees are constant $d \geq 2$ (though the adjacency matrix need not be symmetric).
Suppose further that the graph is strongly connected.
Since the graph is strongly connected, for any two vertices $v$ and $w$, there is a directed path connecting $v$ to $w$.
I am curious about a different kind of path which isn't unidirectional, but "alternating" in a sense.
That is, is there a path
$$v, u_1, u_2, u_3, \dots, u_{2t-1}, w$$
where $(u_1 \to v)$ is a directed edge, but $(u_1 \to u_2)$ is a directed edges, $(u_3 \to u_2)$ is a directed edge, $(u_3 \to u_4)$ is a directed edge, and so on. That is, $u_{2m-1}$ has two directed edges to $u_{2m-2}$ and $u_{2m}$.
So this is a kind of path between $v$ and $w$, but where the directions alternate in a sense.
My question: Is there always such a path connecting any two vertices of the directed graph $G$ which is strongly connected? If not, what properties are necessary for such a result to hold?
P.S. $G$ is not a directed cycle. Thanks to the comment for pointing that out.

A: Consider the following strongly connected digraph with $d=3$ and the problem of finding an alternating path from vertex $0$ to vertex $3$.

Such a path must eventually use either edge $(0,2)$ or edge $(3,1)$.  Let's call these two edges "bridges."  All paths from $0$ back to itself that  cross a bridge have even length and all similarly constrained paths from $0$ to $1$ have odd length.  Hence no matter what alternating path is followed, it can never cross a bridge; hence it cannot connect $0$ to $3$.
EDIT: There is also a counterexample with $d=2$:

From vertex $0$, alternating paths cannot reach vertex $2$.


text:
Q: ag-Grid key handler on empty grid I'm using ag-Grid's onKeyPress and onKeyDown event handlers to set the quickFilter text in an input outside the grid.
When the user types a value that does not exist, the grid will have no rows and onKey* events won't happen anymore. How can I make it possible to catch the i.e. backspace key in this case to update the filter?
I will not accept a solution with attaching event handlers to document/window or using overlays.

A: why don't you use (change) instead of onKey*? and then backspace will trigger the function.


text:
Q: How to access properties of object from Stub? I have simple class:
class MyClass {

    private $myProperty;

    public __construct($propertyValue) {
        $this->myProperty= $propertyValue;
    }

    public function myMethod() {
        // Something
    }

}

And class what using MyClass:
class MySecondClass {

    private $myClass;

    public __construct($myClassInst) {
        $this->myClass = $myClassInst;
    }

    public function doIt() {
        $this->myClass->myMethod();
    }

}

And I have unit test for some MySecondClass class:
use Codeception\TestCase\Test;
use Codeception\Util\Stub;

class MySecondClassTest extends Test

    public function testDoIt() {
        $data = null;

        $myClass = Stub::construct('MyClass', ['propertyValue'], [
            'myMethod' => function() use (&$data) {
                // I want do that, but I can not!
                //$data = $this->myProperty;
            }

        $mySecondClass = new MySecondClass($myClass);
        $mySecondClass->doIt();

        $this->assertEquals($data, 'assertValue');
    ]);

}

If to uncomment lines in example above:
PHP Warning:  Uncaught PHPUnit_Framework_Exception: Undefined variable: myProperty ...

In case of myProperty is public:
PHPUnit_Framework_Exception: Undefined property: MySecondClassTest::$myProperty

Question: How to access property myProperty of MyClass from Stub if $this referencing to object of class MySecondClassTest there?

A: Yagni. You are testing logic in MySecondClass::doIt ,not in MyClass.
You mock MyClass, and define exact response from MyClass::myMethod with constant value. Basically, your testDoIt() reads: Given we have an instance of MyClass that return some exact value, we expect MySecondClass::doIt to return some exact value. That's it. Nothing to do with MyClass::myProperty at all.
EDIT
in answer to the comment

In case of public property it is error too, because $this references to MySecondClassTest object: PHPUnit_Framework_Exception: Undefined property: MySecondClassTest::$myProperty

First of all, I think you misunderstand concept of test doubles. Stub is not an instance of the mocked class. It is a stub. It imitates behaviour of the mocked class, and only in the defined part.
Secondly, $this in a closure always refers to the class where the closure is defined. In your case it is MySecondClassTest.
Again, the problem is not in visibility of the property, but in the fact that you need value of this property in your test. You do not. It violates the core principle of unittesting.


text:
Q: Custom dependency property of image in WPF I have little problem. I want to create custom control and this custom control should have Custom dependencyproperty of type Image. I want to be able to change Image of specific control in design time like it is in standard Image Control. I tried to do it like this:
    public ImageSource IconImageSource
    {
        get { return (ImageSource)GetValue(IconImageSourceProperty); }
        set
        {
            SetValue(IconImageSourceProperty, value);
            img_Icon.Source = value;

        }
    }
    public static DependencyProperty IconImageSourceProperty =
        DependencyProperty.Register("IconImageSource", typeof(ImageSource), typeof(NavigationMenuItem));

then set image source in xaml file like this:
<local:NavigationMenuItem IconImageSource="/res/DarkMode/NavigationMenuItem_Home.png"/>

App is compiling without problem, but it doesnt show my image. Honestly I dont understand what's wrong here, I tried to debug this but I just cant. I set breakpoint in set but it didnt even stopped, like set wouldnt be even launched once. I dont have any idea how can I fix this. I tried to change type to Uri, BitmapImage but nothing helped Can anyone help me please?


text:
Q: Python nested dictionary updating all dicts rather than specified I am scraping results from a web table (link can be found in the code if needed) using BeautifulSoup. I then iterate through the table rows and subsequently iterate through the cells to produce a list of that row's data. That list is indexed to pull out the name of a driver and their lap time which I want to add to a set of nested dictionaries.
However instead of just updating the values (two-levels down) for the dictionary I have specified (one-level down) it updates them for all the dictionaries.
My code (shortened and generalised the races and drivers):
#Imports
import requests
from bs4 import BeautifulSoup as bsoup

dataurls = {
    'race1': 'https://fiaresultsandstatistics.motorsportstats.com/results/2022-bahrain-grand-prix/classification/2c65d50d-606e-4988-81c5-7a4976ef0e6f'
}

#Setup the dictionary
races = ['race1', 'race2']
drivers = ['driver1', 'driver2']
mainDict = dict.fromkeys(races, {})

#Scraping elements
def webscraper(mDict, race):
    soup = bsoup(requests.get(dataurls[race]).content, "html.parser")
    #Dict for races, will contain driver key and lap time value.
    rDict = {}
    #Parse the table by row, extract driver name and lap time
    for tr in soup.find("table", class_="_2Q90P").find_all("tr", class_="_3AoAU"):
        row = ([td.text for td in tr.find_all('td')])
        dDriver = row[2]
        dTime = row[6]
        dDict = {dDriver: dTime}
        rDict.update(dDict)
    mDict[race].update(rDict)
webscraper(mainDict, races[0])
print(mainDict)

Expected output:
{
'race1': {'driver1': '1:30:100', 'driver2': '1:30.200'},
'race2': {}
}

Actual output:
{
'race1': {'driver1': '1:30:100', 'driver2': '1:30.200'},
'race2': {'driver1': '1:30:100', 'driver2': '1:30.200'}
}

I have tried so many different ways to get around it, the only other thing I can get to happen is that only the last drivers' time is added to the correct race only.

A: To solve this problem replace the update function used to update the mDict variable inside the webscraper function with an = sign
#Imports
import requests
from bs4 import BeautifulSoup as bsoup

dataurls = {
    'race1': 'https://fiaresultsandstatistics.motorsportstats.com/results/2022-bahrain-grand-prix/classification/2c65d50d-606e-4988-81c5-7a4976ef0e6f'
}

#Setup the dictionary
races = ['race1', 'race2']
drivers = ['driver1', 'driver2']
mainDict = dict.fromkeys(races, {})

#Scraping elements
def webscraper(mDict, race):
    soup = bsoup(requests.get(dataurls[race]).content, "html.parser")
    #Dict for races, will contain driver key and lap time value.
    rDict = {}
    #Parse the table by row, extract driver name and lap time
    for tr in soup.find("table", class_="_2Q90P").find_all("tr", class_="_3AoAU"):
        row = ([td.text for td in tr.find_all('td')])
        dDriver = row[2]
        dTime = row[6]
        dDict = {dDriver: dTime}
        rDict.update(dDict)
    mDict[race] = rDict
webscraper(mainDict, races[0])
print(mainDict)

or change the way you are using the update:
mDict.update({race: rDict})

https://www.w3schools.com/python/ref_dictionary_update.asp
Apparently the way you are using selects all keys in the dictionary


text:
Q: "are specified" or "have been specified" would be grammatically correct? Which one is correct?

The conditions of deformation and calculation of the soil – pipeline system are specified?

Or:

The conditions of deformation and calculation of the soil – pipeline system have been specified?

A: Are is in the present tense, whereas have been is in the past tense.
Therefore, if hey have just been specified use:

The conditions of deformation and calculation of the soil – pipeline system are specified?

If they have been specified for a while, use:

The conditions of deformation and calculation of the soil – pipeline system have been specified?

A: I agree with D Manokhin and I'll add another point of view.
(1) In other papers on the subject, the conditions have been specified. Our research is based on those prior conditions.
(2) In this paper, the conditions (on which we base our conclusions) are specified.


text:
Q: Copy file full path in Xcode I'm using Perforce for managing our code base. In Perforce, we need to check out a file before we can edit it. When I'm working in Xcode, sometimes I want to know the full path to the working file so that I can check it out in Perforce.
So here is my question:
Is there a shortcut, plugin or some other quick way to copy the full path of a file in Xcode?
What I have known:

*

*I can Command+click on the file tile to show up the full path, but I cannot copy it.

*In Visual Studio, we can right click on the file's tab and choose Copy Full Path to achieve this.

*In Eclipse, we can Alt/Option + Enter to achieve this.

Update:
Actually my question is about how to achieve the equivalent Copy Full Path feature inside Xcode. Anyway, dragging the file to the terminal is also a very nice workaround.

A: You can copy it directly out of the File Inspector. The first section ("Identity and Type") of the File Inspector shows information about the selected file, or the file that contains the selected symbol, etc. You have Name, Type, Location, and Full Path. You can select the full path and copy it.
As a shortcut, a triple click on any part of the path will select the entire path. There's also a small icon with a light arrow on a dark background -- clicking that will open a Finder window with the file selected.

A: You can drag it to a terminal... Easy and fast...

A: on your editor XCode (you want to get the file path). Press:
Command+Shift+J

xcode will open directory file path on Project Navigator (left side bar)
and then drag-and-drop file from Project Navigator to the terminal. it will give you the directory of the file.

A: You can use find command to copy file path:
cd myProject
find . -name myCodeFile.cpp

A: Extending Caleb's answer, here is a graphical demo:
Steps:

*

*Select a filename on the Project navigator from the left side Navigator panel.

*Tap on Show File Inspector from the right side Inspectors panel. (marked with red box)

*Copy the path from there. (marked with a bigger red box)


text:
Q: Usage rule for verbs being used in singular and plural form after pronouns If there is singular pronoun like it,   she/he ; the verb succeeding the pronoun should be singular form or plural. Is there any sentence construction rule?

*

*
It gives you

*
It give you

Also with  pronoun like they, that ; how it should be used

*

*
They give you.

*
They gives you

A: The 'rule' is exactly the same with a pronoun as with a noun. So you would write "The son gives you" and not "The son give you". Similarly "the children give you" and not "the children gives you".


text:
Q: Time Efficient Frequency Count (top 500 words) of a Large Directory in Python? I wish to calculate the top 500 words (in terms of occurrence) for all the files (a maximum of 15,000 files) of a directory. I am experimenting the same on small sized directories containing  1000 files. For these 1000 files, I am getting results, but time efficiency is not preserved. It takes too much time to process.
Firstly, I have merged all the files into a single file, namely combined.txt, which is the input file (using TXTcollector). Then I have pre-processed (stopwords, lowercase and lemmas and pos tagging) it and computed the top 500 words with the help of nltk FreqDist().
Combined.txt is the input file and it contains data's from multiple text files separated by ==== (delimiter).
At present, my code is very slow in terms of performance. This is because For a 36 Kb file (combining all the files of a directory) : the below mentioned code takes 4.6 sec and for 8888 MB file (combining all the files of a directory) it's taking 672 sec to process. And further, when the size will get increased, then the code will be in-efficient in terms of time, also same happens, if the size of the file in the directory escalates.
Note: I am using Windows 10, 64 bit, Python 3.7 and my editor is Sublime-text. I have computed the elapsed time, from the editor itself.
The code is as follows:
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize.regexp import wordpunct_tokenize
from nltk.corpus import stopwords
from nltk.data import load
from nltk.tokenize import word_tokenize, RegexpTokenizer

_POS_TAGGER = 'taggers/maxent_treebank_pos_tagger/english.pickle'
tagger = load(_POS_TAGGER)
regexp_tagger = nltk.tag.RegexpTagger([(r'\(|\)', '--')], backoff = tagger)

def read_data():
    with open("path", 'r', encoding='utf-8', errors = 'replace') as f:
        raw_data = f.read()
        global text
        text = '\n'.join(nltk.line_tokenize(raw_data.lower()))
read_data()

def preprocess():
    stop_words = set(stopwords.words("english"))
    tokens = nltk.word_tokenize(text)
    pos_text = regexp_tagger.tag(tokens)
    names = [n.encode('utf-8') for n,pos in pos_text if (pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS')]
    names_text = (' '.join(map(bytes.decode, names))).strip()
    tokens = [t for t in wordpunct_tokenize(names_text)]
    tokens = filter(lambda x: x not in stop_words, tokens)
    tokens = filter(lambda x: x.isalpha(), tokens)
    tokens = filter(lambda x: len(x) > 1, tokens)
    wordnet_lemmatizer = WordNetLemmatizer()
    global lemmatized_tokens
    lemmatized_tokens = [wordnet_lemmatizer.lemmatize(t) for t in tokens]

preprocess()

def freq_count():
    fd = nltk.FreqDist(lemmatized_tokens)
    print(fd.most_common(500))
freq_count()

How to achieve efficient results in terms of time?


text:
Q: getting this error on SQL - Syntax error: Expected end of input but got identifier "ROUND" at [4:1] for COUNT function SELECT usertype,
   CONCAT(start_station_name, " to ", end_station_name) AS route
   COUNT(SUM(Row) AS num_trips
   ROUND(AVG(cast(tripduration as int64)/60), 2) AS duration
FROM `bigquery-public-data.new_york_citibike.citibike_trips`
GROUP BY start_station_name, end_station_name, usertype
ORDER BY
num_trips DESC
LIMIT 10

A: Please, correct syntax as per below, where you missing ")" after "COUNT(SUM(Row)":

SELECT usertype,    CONCAT(start_station_name, " to ",
end_station_name) AS route    COUNT(SUM(Row)) AS num_trips
ROUND(AVG(cast(tripduration as int64)/60), 2) AS duration FROM
bigquery-public-data.new_york_citibike.citibike_trips  GROUP BY
start_station_name, end_station_name, usertype ORDER BY  num_trips
DESC LIMIT 10


text:
Q: How to keep the only the top N values in a dataframe It is pandas/Dataframe, for every row, I want to keep only the top N (N=3) values and set others to nan,
import pandas as pd
import numpy as np

data = np.array([['','day1','day2','day3','day4','day5'],
                ['larry',1,4,4,3,5],
                ['gunnar',2,-1,3,4,4],
                ['tin',-2,5,5, 6,7]])

df = pd.DataFrame(data=data[1:,1:],
                  index=data[1:,0],
                  columns=data[0,1:])
print(df)

output is
       day1 day2 day3 day4 day5
larry     1    4    4    3    5
gunnar    2   -1    3    4    4
tin      -2    5    5    6    7

I want to get
       day1 day2 day3 day4 day5
larry   NaN    4    4  NaN    5
gunnar  NaN  NaN    3    4    4
tin     NaN    5  NaN    6    7

Similar to pandas: Keep only top n values and set others to 0, but I need to keep only N highest available values, otherwise the average is not correct
For the result above I want to keep first 5 only

A: You can use np.unique to sort and find the 5th largest value, and use where:
uniques = np.unique(df)

# what happens if len(uniques) < 5?
thresh = uniques[-5]
df.where(df >= thresh)

Output:
        day1  day2  day3  day4  day5
larry    NaN   4.0     4     3     5
gunnar   NaN   NaN     3     4     4
tin      NaN   5.0     5     6     7

Update: On the second look, I think you can do:
df.apply(pd.Series.nlargest, n=3,axis=1).reindex(df.columns, axis=1)

Output:
        day1  day2  day3  day4  day5
larry    NaN   4.0   4.0   NaN   5.0
gunnar   NaN   NaN   3.0   4.0   4.0
tin      NaN   5.0   NaN   6.0   7.0

A: To keep, for every row, the top 3 values you can use:
df = (df * df.astype(float).apply(lambda x: x.isin(x.nlargest(3)), axis=1)).replace('', np.nan)

You can migrate nlargest's parameter into a variable if needed.
Output:
        day1 day2 day3 day4 day5
larry    NaN    4    4  NaN    5
gunnar   NaN  NaN    3    4    4
tin      NaN    5    5    6    7

A: stack, sort, keep the top 3 per row with a groupby, and then unstack. We need a mergesort to ensure we always keep the first value per row in the case of ties.  Reindex ensures we have all the original columns if there are no largest values in any of the rows for that column.
If you require Int in the end, the best you can do is 'Int64', pandas nullable-integer dtype.
# df = df.apply(pd.to_numeric)  # To make numeric, not object.

N = 3
(df.stack()
   .sort_values(ascending=False, , kind='mergesort')
   .groupby(level=0).head(N)
   .unstack()
   .reindex(df.columns, axis=1)
   .astype('Int64'))

        day1  day2  day3  day4  day5
larry   <NA>     4     4  <NA>     5
gunnar  <NA>  <NA>     3     4     4
tin     <NA>     5  <NA>     6     7

Here are some timings vs the number of rows, and proof that these three methods are equivalent (before any type-casting). @anky's solution is very fast and simple.
import perfplot
import pandas as pd
import numpy as np

def alollz_stack(df, N=3):
    return (df.stack()
              .sort_values(ascending=False, kind='mergesort')
              .groupby(level=0).head(N)
              .unstack()
              .reindex(df.columns, axis=1))

def quang_nlargest(df, N=3):
    return df.apply(pd.Series.nlargest, n=N, axis=1).reindex(df.columns, axis=1)

def anky_rank(df, N=3):
    return df[df.iloc[:,::-1].rank(1,'first').ge(df.shape[1]-N+1)]

perfplot.show(
    setup=lambda n: pd.DataFrame(np.random.randint(0, 100, (n, 5)),
                                 columns=[f'col{i}' for i in range(1,6)]),
    kernels=[
        lambda df: alollz_stack(df),
        lambda df: quang_nlargest(df),
        lambda df: anky_rank(df)],
    labels=['Stack', 'Apply_Nlargest', 'Rank'],
    n_range=[2 ** k for k in range(18)],
    equality_check=lambda x,y: np.allclose(x,y, equal_nan=True),
    xlabel='N_rows'
)

A: Here is another way using df.rank on axis=1 , we reverse the columns and calculate the rank since on a duplicate you want to retain the first value.
df[df.astype(float).iloc[:,::-1].rank(1,'first').ge(3)]

       day1 day2 day3 day4 day5
larry   NaN    4    4  NaN    5
gunnar  NaN  NaN    3    4    4
tin     NaN    5  NaN    6    7

however as @Allolz rightly directed, for a general usecase based on the shape of the df, one can use:
N=3
n = df.shape[1]-N+1
df[df.astype(float).iloc[:,::-1].rank(1,'first').ge(n)]


text:
Q: Read and write hard disk sector directly and efficiently I have a special need for block data storage. My data are formatted data blocks in size of 4096. For high efficiency, I want to directly manipulate the block on hard disk sector and do not want to treat the data block as file. I think one way is to treat the device as a file such as /dev/sda1 and to use lseek() read() and write() to read and write data. However I do not know the whether the head of the file is the first sector of hard disk. I also suspect the efficiency of this method.
I am working on Linux OS and C programming language.
What is the most efficient way to handle the sector of hard disk? Should I write an block device module of linux. However, I do not know much about it. What kernel functions should I use to read and write on block device?

A: "Blocks in size of 4096" is not a special need, and you have not mentioned any access patterns that would break the kernel's built-in caching mechanisms.
The most efficient way to read and write your data is to use a file.

A: int ReadSector(int numSector,char* buf)
{
    int retCode = 0;
    BYTE sector[512];
    DWORD bytesRead;
    HANDLE device = NULL;

    device = CreateFile("\\\\.\\H:",    // Drive to open
        GENERIC_READ,           // Access mode
        FILE_SHARE_READ,        // Share Mode
        NULL,                   // Security Descriptor
        OPEN_EXISTING,          // How to create
        0,                      // File attributes
        NULL);                  // Handle to template

    if(device != NULL)
    {
        // Read one sector
        SetFilePointer (device, numSector*512, NULL, FILE_BEGIN) ;

        if (!ReadFile(device, sector, 512, &bytesRead, NULL))
        {
            Print("Error in reading1 floppy disk\n",numligne++);
        }
        else
        {
            // Copy boot sector into buffer and set retCode
            memcpy(buf,sector, 512);retCode=1;
        }

        CloseHandle(device);
        // Close the handle
    }

    return retCode;
}

This my function to read sectors and it is same maner to write.
Sector zero will be first sector of a partition