text:
Q: How to search for a partial string in a dataframe and return a specific cell using Pandas? I've got a dataframe with non-standard columns (not the same info all the way down). I want to search for a particular phrase that may or may not appear in some column of a row and then return the value of the succeeding cell. For example:
A               B               C
How many?       5               Blah blah
Blah            How many?       7
How many?       13              Blah
Blah            Blah            Blah

I'm trying to figure out how to search for the phrase "How many?" and then return the value in the next cell (5/7/13/null)

A: With Boolean and shift
df[df.eq('How many?').shift(1,axis=1).fillna(False)]
Out[142]:
     A    B    C
0  NaN    5  NaN
1  NaN  NaN    7
2  NaN   13  NaN
3  NaN  NaN  NaN

Update
s1=df.eq('How many?').shift(1,axis=1).fillna(False)
s2=df.eq('How many?')
df[s1|s2]
Out[154]:
          A          B    C
0  How many?         5  NaN
1       NaN  How many?    7
2  How many?        13  NaN
3       NaN        NaN  NaN

A: Use numpy array instead for easier indexing:
mask = df.values == 'How many?'
your_list = [df.values[i, j+1] for i, j in zip(*np.where(mask)) if j < df.values.shape[1]-1]
# yourlist = ['5', '7', '13']


text:
Q: List users permissions to tables and schemas on MSSQL 2016 List all permissions for a given role? has a nice query for listing users and their roles on a DB.
How could we list all tables and users with their permissions on these tables?

A: Give this a shot.
SELECT ST.NAME, su.name,
CASE WHEN SYP.[ACTION] = 193 THEN 'SELECT' WHEN SYP.[ACTION] = 195 THEN 'INSERT' WHEN SYP.[ACTION] = 196 THEN 'DELETE' WHEN SYP.[ACTION] = 197 THEN 'UPDATE' ELSE CAST(SYP.[ACTION] AS CHAR(3)) END AS Permission
FROM
SYS.SYSPROTECTS SYP INNER JOIN
SYS.SYSUSERS SU
ON SU.uid = SYP.UID
INNER JOIN SYS.SYSOBJECTS SO
ON SO.id = SYP.id
INNER JOIN SYS.TABLES ST
ON ST.object_id = SO.id

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to track mobile numbers who revert with START keyword to re-optin can someone tell me how to track the 'Mobile-Optin' Keyword using dataview in marketing cloud? When a person receives the SMS, he will revert with 'STOP' to optout (which I'm able to track using _smsmessagetracking dataview.) Similarly I have set up a Mobile optin message for 'START' keyword to re-optin for the subscribers who have reverted with 'STOP'.
How do I track these phone numbers who has reverted with 'START' using dataview. When I run the below query, it's not showing any data.
Select *
from ENT._smsmessagetracking
where
MessageText in ('START','STOP')

A: Assuming you are using 'START' as the opt-in keyword and 'STOP' as the opt-out keyword, and the customers did receive and send text with those keywords like you mentioned above.
I would leverage the _MobileSubscription data view to know which keyword status for each mobile number.
Note: "This Data View is officially unsupported by Salesforce. Marketing Cloud still fills it with data, but there is no guarantee of how long it will persist or whether it will be correct." Reference
But first, you need to get the "SubscriptionDefinitionID" for each keyword, I would use _SMSMessageTracking data view since the customers did receive and send text with those keywords.
SELECT DISTINCT
KeywordID,
SharedKeyword
FROM
_SMSMessageTracking
WHERE
SharedKeyword = 'START' OR
SharedKeyword = 'STOP'

The "KeywordID" field in this data view equals with "SubscriptionDefinitionID" in _MobileSubscription so you can use value of this field to map with the corresponding "_SubscriptionDefinitionID" field below
SELECT
CASE
    WHEN mobileSub._SubscriptionDefinitionID = 'KeywordID for START keyword' THEN 'JCC'
    WHEN mobileSub._SubscriptionDefinitionID = 'KeywordID for STOP keyword' THEN 'JCCSTOP'
END AS Keyword
    , mobileSub._MobileNumber             AS MobileNumber
    , mobileSub._OptOutStatusID           AS OptOutStatusID
    , mobileSub._OptOutMethodID           AS OptOutMethodID
    , mobileSub._OptOutDate               AS OptOutDate
    , mobileSub._OptInStatusID            AS OptInStatusID
    , mobileSub._OptInMethodID            AS OptInMethodID
    , mobileSub._OptInDate                AS OptInDate
    , mobileSub._Source                   AS Source
    , mobileSub._CreatedDate              AS CreatedDate
    , mobileSub._CreatedBy                AS CreatedBy
    , mobileSub._ModifiedDate             AS ModifiedDate
    , mobileSub._ModifiedBy               AS ModifiedBy
FROM _MobileSubscription AS mobileSub
WHERE mobileSub._SubscriptionDefinitionID IN ('KeywordID for START keyword', 'KeywordID for STOP keyword')

You can track many useful information in the result, like each mobile number opt-in and opt-out date
Note 2: Subscription Status here can be understood by numeric values
***Opt-in***
OptInStatusID: 2
OptOutStatusID: 0

***Opt-out***
OptInStatusID: 0
OptOutStatusID: 1

Note 3: I don't think the "stop" keyword will show up in the results, normally when a person sends a message with a stop keyword, it will opt-out other opt-in keywords. But you should give a try and figure out by yourself.


text:
Q: Log-Sobolev constant Let $\nu \propto e^{-f}$ be a probability density on $\mathbb{R}^d$ with full support. We say $\nu$ satisfies the log-Sobolev inequality (LSI) with constant $\alpha$ if for every smooth function $g:\mathbb{R}^d \to \mathbb{R}$, we have
$$
\mathbb{E}_\nu [g^2 \log g^2] - \mathbb{E}_\nu[g^2] \log\mathbb{E}_\nu[g^2] \leq \frac{2}{\alpha} \mathbb{E}_\nu[|\nabla g |^2]
$$
If $f$ is $\mu$-strongly convex (or equivalently $\lambda_{\min} (\nabla^2 f(x)) \geq \mu $, for some constant $\mu >0$), then it is well-known that $\nu$ satisfies LSI with constant $\alpha =\mu$.
Now, suppose
$$\lambda_{\min} (\nabla^2 f(x)) \geq \mu \frac{|x|}{1+|x|}.$$
What is the LSI constant $\alpha$ in this case ? Specifically, will it be polynomial or exponential in $d$, or independent of $d$ ?


text:
Q: Improve the speed for ST_DWithin I need to get the outer polygon of the LSOAs within 10 miles of each postcode centroid. There are 180k LSOA polygons in table1 and 2.6 million postcode centroid points in table2.
I have created 2 geography columns (polygon.geog, pois.geog) and one geometry column polygon.coordinates. All of them are indexed using GIST.
I tried running for 10 using the code below which took 1 minute.
SELECT pois.objectid, ST_Multi(ST_Union(polygon.coordinates)) as coords
              into table3
              FROM table1 as polygon
              INNER JOIN table2 as pois
              ON ST_DWithin(polygon.geog,pois.geog, 10* 1609.34,false)
              group by pois.objectid
            limit 10;

Query plan,

[
  {
    "Plan": {
      "Startup Cost": 0.84,
      "Plans": [
        {
          "Partial Mode": "Simple",
          "Startup Cost": 0.84,
          "Plans": [
            {
              "Startup Cost": 0.84,
              "Plans": [
                {
                  "Startup Cost": 0.43,
                  "Scan Direction": "Forward",
                  "Plan Width": 39,
                  "Node Type": "Index Scan",
                  "Plan Rows": 3011500,
                  "Relation Name": "table2",
                  "Alias": "pois",
                  "Parallel Aware": false,
                  "Parent Relationship": "Outer",
                  "Total Cost": 11352214.75,
                  "Index Name": "postcode_pkey"
                },
                {
                  "Filter": "(((pois.geog)::geography && _st_expand(geog, '16093.4'::double precision)) AND _st_dwithin(geog, (pois.geog)::geography, '16093.4'::double precision, false))",
                  "Startup Cost": 0.41,
                  "Scan Direction": "NoMovement",
                  "Plan Width": 11560,
                  "Node Type": "Index Scan",
                  "Index Cond": "(geog && _st_expand((pois.geog)::geography, '16093.4'::double precision))",
                  "Plan Rows": 1,
                  "Relation Name": "table1",
                  "Alias": "polygon",
                  "Parallel Aware": false,
                  "Parent Relationship": "Inner",
                  "Total Cost": 78.31,
                  "Index Name": "gidgeo"
                }
              ],
              "Node Type": "Nested Loop",
              "Plan Rows": 181100,
              "Join Type": "Inner",
              "Parallel Aware": false,
              "Parent Relationship": "Outer",
              "Plan Width": 5783,
              "Total Cost": 247219664.75
            }
          ],
          "Node Type": "Aggregate",
          "Strategy": "Sorted",
          "Plan Rows": 181100,
          "Parallel Aware": false,
          "Group Key": [
            "pois.objectid"
          ],
          "Parent Relationship": "Outer",
          "Plan Width": 39,
          "Total Cost": 247223286.75
        }
      ],
      "Node Type": "Limit",
      "Plan Rows": 1,
      "Parallel Aware": false,
      "Plan Width": 39,
      "Total Cost": 1365.96
    }
  }
]

Is it possible to improve the speed of this code?


text:
Q: Columns vertical lines disappeared I have removed few columns from excel file and saved it. When I open it again columns(A, B, C) lines has been removed automatically. I happened with me every time I removed the columns of file
How can get vertical lines back ?


text:
Q: Class pointer member pointing to that class: unresolved external symbol I have following header and source code that
declare a class with a member variable. The member variable is a smart pointer pointing to that class. When I try to assign a value to the pointer, the program fails to build with error: unresolved external symbol. Can sombody explain to me why this is the case?
Header.h

#pragma once
#include <mutex>

using namespace std;

class myClass {
public:
    static shared_ptr<myClass> ptr;
};

class myClass2 : public myClass {

};

Class.cpp

#include "stdafx.h"
#include "Header.h"
#include <utility>

int main()
{

    myClass instance1;
    myClass instance2;
    myClass2 instance3;

    instance2.ptr = make_shared<myClass>(instance3);
    return 0;
}

A: In your code, ptr is a class variable rather than a instance variable since you define it to be static in header.h.  If you want to treat the ptr member as an instance member, you should remove the static declaration.

A: Declaring a static member usually requires you to allocate storage outside the class for the static member. More info here:
http://en.cppreference.com/w/cpp/language/static
Add a
shared_ptr<myClass> myClass::ptr;

to one of your cpp files to allocate storage.
But you are using the static member as an instance member, bringing into question whether on not you want a static member at all.


text:
Q: UWP cant write/read any file im trying to write data to file in UWP.

Error that crashes: "Exception thrown:" System.Exception "in System.Private.CoreLib.dll
System.Exception: The APPX file cannot be accessed because it was not encrypted as expected (Exception from HRESULT: 0x80070199) ".

I tried to search for the error code on the internet but I found absolutely nothing. When im trying to open created file using notepad it throws the same error.
Here some code
public static async void CreateDirectory(string name)
    {
        IReadOnlyList<IStorageItem> itemsList = await DirectoriesFolder.GetItemsAsync();
        int newId = itemsList.Count + 1;
        StorageFolder newDir = await DirectoriesFolder.CreateFolderAsync(newId.ToString());
        StorageFile cfgFile = await newDir.CreateFileAsync("DIRECTORYDATADONOTMODIFYORDELETETHISFILE.ddsf");

        try
        {
            var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary("dupa", Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
            //DirectoryConfigJson(newId, name)
            await FileIO.WriteBufferAsync(cfgFile, buffer); // this causes error

        } catch(Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }
        ObservableCollection<DirFile> dfList = new ObservableCollection<DirFile>();
    }


text:
Q: Joi validate 2 schemas conditionally - Invalid schema content I'm trying to add conidial schema according of the value of the isCat field in the request body, here is what I have so far:
ror [ERR_ASSERTION]: Invalid schema content` error.What am I missing? Thanks.

A: Try this
Joi.object({
  params: Joi.object({
    id: Joi.number().required().integer().min(1),
  }),
  body: Joi.object({
    code: Joi.string().required(),
  }).when(Joi.ref("$isValid"), {
    is: Joi.equal(true),
    then: Joi.object({
      body: Joi.object({
        ...entity,
      }),
    }),
    otherwise: Joi.object({
      body: Joi.object({
        ...put,
      }),
    }),
  }),
});

Verify the reference given by you is right Joi.ref("$isValid").
If you provide right reference, this schema will work as you expect.


text:
Q: Broken pipe error when proxying long file upload request Recently and overnight, Apache's error logs from a couple of nodejs servers have been filling with this:

[proxy:error] [pid xxx] (32)Broken pipe: [client xxx.xxx.xxx.xxx:59835] AH01084: pass request body failed to 127.0.0.1:9001 (127.0.0.1), referer: https://tubedu.org/videos/upload

And

[proxy_http:error] [pid xxx] [client xxx.xxx.xxx.xxx:59835] AH01097: pass request body failed to 127.0.0.1:9001 (127.0.0.1) from xxx.xxx.xxx.xxx (), referer: https://tubedu.org/videos/upload

It happens when users try to upload large files. When the transfer is done, users get a 502 bad gateway error. This happens randomly but the larger is the file, most likely it is to happen.
Thanks!
EDIT: It seems that the error happens 60 seconds before de connection is established. About the first error message, sometimes it shows that one and sometimes shows this one:

[proxy:error] [pid xxx] (104)Connection reset by peer: [client xxx.xxx.xxx.xxx:58520] AH01084: pass request body failed to 127.0.0.1:9000 (127.0.0.1), referer: https://video.hardlimit.com/videos/upload

I've tried increasing timeouts in apache2.conf like this:
Timeout 900
ProxyTimeout 900
KeepAliveTimeout 600

with no result.
Finally, I've added to my virtualhost, this:
Timeout 600
ProxyTimeout 600

and this:
ProxyPass /           http://127.0.0.1:9000/ timeout=600
ProxyPassReverse / http://127.0.0.1:9000/ timeout=600

But the error always happens 60 seconds before the transfer begins.
EDIT 2: I've modified the value of /proc/sys/net/ipv4/tcp_fin_timeout to 120 (it was 60). But it didn't work.
EDIT 3: Apparently it is a new "feature" of NodeJS 12.19.0 witch kills the connection 60 seconds before it is established. I solved it by using Nginx. This web server make a new connection just when the file has been uploaded to its buffer. Then, the server transfers it thru NodeJS witch takes way less than 60 seconds.


text:
Q: d'Alembert solution to wave equation Suppose we are solving the wave equation in one dimension as given by:
$$
u_{tt} - c^2 u_{xx} = 0 , \quad x \in \mathbb{R}, t>0 \\
u(x,0) = \phi(x), \qquad x \in \mathbb{R} \\
u_t(x,0) = c \phi'(x), \quad x \in \mathbb{R}\\
$$
d'Alembert's solution gives us that $$ u(x,t) = \frac{1}{2} \left( \phi(x+ct) + \phi(x-ct) \right) + \frac{1}{2c}\int_{x-ct}^{x+ct} c\phi'(y) dy$$
When we evaluate the integral as $\frac{1}{2}( \phi(x +ct) - \phi(x-ct))$, the solution is then $$ u(x,t) = \phi(x+ct)$$
Which seems counterintuitive to me. Interpretting the d'Alembert solution as a  left and right moving wave, we get that the left moving wave doesn't exist?
[This question arises from a problem to find the solution to the wave equation (in one dimension) on two media seperated at the origin, with the inital displacement only in $x>0$, which would mean the wave only travels away from the boundary, so no question at all?]

A: The boundary condition $u_t(x,0) = c \phi'
(x)$ is very special, causing exactly the cancellation you observe.  Changing this boundary condition to $u_t(x,0) = - c \phi'(x)$ cancels the other wave.  (I recall; I haven't checked whether the other boundary condition must be tweaked also.)


text:
Q: xpathApply returns NULL object I have been trying to scrape from a soccer site a table of players as well as links to individual player's profile. I use Chrome's Inspect element to get the xpath (is that a good idea?), and yet I got no result still.
The web page is Liverpool's page. Below is my attempt to scrape both the player table and the links to each player profile.
require(XML)

team_name <- "Liverpool"
url <- paste("http://www.football-lineups.com/team/", team_name,
             "/Champions_League_2004_2005/Stats/Most_Capped/", sep='')
url.data <- htmlParse(url)
table <- xpathApply(url.data,
  '//*[@id="mainarea"]/tbody/tr/td[1]/table[2]', xmlValue)
links <- xpathApply(url.data,
  '//*[@id="mainarea"]/tbody/tr/td[1]/table[2]/tbody/tr[2]/td[2]/a/@href', xmlValue)
table #NULL
links #NULL

EDIT: Scrapping all the links on the web page work, however. I must do something wrong above!
links2 <- xpathSApply(url.data, "//a/@href")
links2 # a bunch of links


text:
Q: How to check the camera is auto focused in flutter? I am using Camera plugin for my flutter app, how can I check the camera preview is focused or not?

A: Auto Focus will be provided in this milestone,
based on Future of the Camera Plugin (Refactor/Rework) https://github.com/flutter/flutter/issues/31225
IOS part has pull request, please reference [camera] Expose auto exposure and auto focus point of interest functionality (iOS only) https://github.com/flutter/plugins/pull/709


text:
Q: Android Not Saving Files I've been doing some work in Android, and I've found after three or four different attempts, I can't seem to get Android to save my file anywhere. In fact, it doesn't even create a folder in data/ for my app.
Here's how I'm trying to save the file - this is in my main activity also.
@Override
public void onStop(){
    super.onStop();

    try{
        FileOutputStream memboricOut = getApplicationContext().openFileOutput("memboric.core", Context.MODE_PRIVATE);
        brain.save(memboricOut);
    }catch(Exception e){
        System.err.println("Could not save memboric core.");
        e.printStackTrace();
    }
}

And inside brain.save():
public boolean save(FileOutputStream fileOut) {
    try{
        ObjectOutputStream oo = new ObjectOutputStream(fileOut);
        oo.writeObject(this);
        oo.close();
        fileOut.close();
        System.out.println("Memboric Core saved successfully.");
        return true;
    }catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}

This code seems to do nothing. I've also placed the saving in onDestroy as well.
Have I just chosen bad placement for the saving? I can't imagine what could possibly being going wrong.

A: Do you have the permission to save files ?
You can add that by adding android.permission.WRITE_EXTERNAL_STORAGE permission to you AnroidManifest.xml.

A:
oo.writeObject(this);

Is brain have serializable data?
Class Brain implements java.io.Serializable {
    public String toString() {
        return "serialized data";
    }
}

If not, DataOutputStream maybe a better choice.
DataOutputStream oo = new DataOutputStream(fileOut);
oo.writeInt(value); // if breain have int value
oo.flush();
oo.close();

Saved data will be appear in /data/data/(your.package.name)/files/memboric.core
Check the file with emulator (or rooted device).


text:
Q: How do I keep a tkinter GUI responsive when running a subprocess for its stdout? So I'm trying to make a GUI for my python script with Tkinter. I want I fairly simple just window where you can type the IP you want to ping and a button to execute the command. Here is my script:
import os
address = input("Enter Ip Here:")
os.system(f"ping {address} -t -l 65500")

So basically what I want is to be able to type the {address} in a small window and then press a button below to execute this but I can't figure out how to do this. (I have already tried the script and it works in the cmd prompt. I just want a GUI for it. Help would be appreciated!
I also made a separate script which opens a window with Tkinter and it has an exit button to close the window:
import Tkinter as tk
from Tkinter import ttk

# root window
root = tk.Tk()
root.geometry('600x600')
root.resizable(False, False)
root.title('Ping Of Death')

# exit button
exit_button = ttk.Button(
    root,
    text='Execute',
    command=lambda: root.quit()
)

exit_button.pack(
    ipadx=5,
    ipady=5,
    expand=True
)

root.mainloop()

A: Try this. Used ip address or hostname.
import functools
import os
import tkinter as tk
from concurrent import futures

thread_pool_executor = futures.ThreadPoolExecutor(max_workers=1)

def tk_after(target):

    @functools.wraps(target)
    def wrapper(self, *args, **kwargs):
        args = (self,) + args
        self.after(0, target, *args, **kwargs)

    return wrapper

def submit_to_pool_executor(executor):

    def decorator(target):

        @functools.wraps(target)
        def wrapper(*args, **kwargs):
            return executor.submit(target, *args, **kwargs)

        return wrapper

    return decorator

class MainFrame(tk.Frame):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.master.geometry('500x350')
        self.master.title("Get output inside GUI")
        self.entry = tk.StringVar()
        label = tk.Label(
            self.master, text="Enter target IP or host as required.")
        label.pack()
        entry = tk.Entry(self.master, textvariable=self.entry)
        entry.insert(-1, "8.8.8.8")
        entry.pack()
        self.button = tk.Button(
            self.master, text="Ping Test", command=self.on_button)
        self.button.pack()
        self.text = tk.Text(self.master)
        self.text.config(state=tk.DISABLED)
        self.text.pack(padx=5, pady=5)

    @tk_after
    def button_state(self, enabled=True):
        state = tk.NORMAL
        if not enabled:
            state = tk.DISABLED
        self.button.config(state=state)

    @tk_after
    def clear_text(self):
        self.text.config(state=tk.NORMAL)
        self.text.delete(1.0, tk.END)
        self.text.config(state=tk.DISABLED)

    @tk_after
    def insert_text(self, text):
        self.text.config(state=tk.NORMAL)
        self.text.insert(tk.END, text)
        self.text.config(state=tk.DISABLED)

    def on_button(self):
        self.ping()

    @submit_to_pool_executor(thread_pool_executor)
    def ping(self):
        self.button_state(False)
        self.clear_text()
        self.insert_text(f'Starting ping request')

        result = os.popen(f"ping {self.entry.get()} -n 2")
        for line in result:
            self.insert_text(line)

        self.insert_text(f'ping request finished')
        self.button_state(True)

if __name__ == '__main__':
    app = tk.Tk()
    main_frame = MainFrame()
    app.mainloop()

A: In order to do this you need to add an Entry to your window and execute your ping with address being set to the value of the entry once your button is pressed. Here is a simple example on how this could work:
import tkinter as tk

def ping(address):
    import os
    os.system(f"ping {address} -t -l 65500")

root = tk.Tk()
root.geometry('600x600')
root.resizable(False, False)
root.title('Ping Of Death')

ip_input_label = tk.Label(root, text="IP: ")
ip_input_label.grid(row=0, column=0)

ip_input = tk.Entry(root)
ip_input.grid(row=0, column=1)

button = tk.Button(root, text="Ping", command=lambda: ping(ip_input.get()))
button.grid(row=1, column=0)

root.mainloop()


text:
Q: Jquery dragabble containment - selector not working My JQuery draggable containment is not working .It keeps going beyond the boundaries set for it. Any help is appreciated.
     $(function() {
        $( "#crop_square" ).draggable();
        containment: "#area_c"

     });

A: You're not appending the containment option correctly, do it this way (passing the option as an argument to the plugin call) :
 $( "#crop_square" ).draggable({
    containment: "#area_c"
 });

Working snippet below :

 $(function() {
        $( "#crop_square" ).draggable({ containment: "#area_c" });
 });

drag

More infos on the draggable widget options here.


text:
Q: Botkit With Express The documentation at Botkit (https://github.com/howdyai/botkit/blob/master/readme-facebook.md) is pretty not meaningful at all:
// if you are already using Express, you can use your own server instance...
// see "Use BotKit with an Express web server"
controller.setupWebserver(process.env.port,function(err,webserver) {
  controller.createWebhookEndpoints(controller.webserver, bot, function() {
      console.log('This bot is online!!!');
  });
});

Moreover, without a custom webserver (like express), Botkit doesnt provide a way to set the custom local url (instead, it simply chooses 0.0.0.0, which is impractical).
Is anyone successfully assembling app = require('express')(); into the setupWebserver in Botkit (specially for Messenger). If yes, please present the full code.

A: Hostname for the built in express server can be set when creating your controller:
var controller = Botkit.facebookbot({
  hostname: 'YOUR_HOST_NAME',
  verify_token: '',
  access_token: ''
})

controller.setupWebserver and controller.createWebhookEndpoints are helper functions within botkit to do just what they describe, create an express webserver and webhook endpoints, respectively.
To implement your own webserver, you just need to setup a webhook endpoint for the botkit controller to receive message POST data at and perform auth handshakes.
By botkit convention this is /{platform}/receive so for facebook /facebook/receive but you can use whatever you like.

To use a custom express server with Botkit, first create a basic webserver.
// components/express_webserver.js

var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var debug = require('debug')('botkit:webserver');

module.exports = function(controller, bot) {

    var webserver = express();
    webserver.use(bodyParser.json());
    webserver.use(bodyParser.urlencoded({ extended: true }));

    webserver.use(express.static('public'));

    // You can pass in whatever hostname you want as the second argument
    // of the express listen function, it defaults to 0.0.0.0 aka localhost
    webserver.listen(process.env.PORT || 3000,  null, function() {

        console.log('Express webserver configured and listening at ',
            process.env.HOSTNAME || 'http://localhost/' + ':' + process.env.PORT || 3000);

    });

    // Register our routes, in this case we're just using one route
    // for all incoming requests from FB
    // We are passing in the webserver we created, and the botkit
    // controller into our routes file so we can extend both of them
    require('./routes/incoming-webhook')(webserver, controller)

    controller.webserver = webserver;

    return webserver;

}

Next you need to create the routes for webhook endpoints, we're doing this in a separate file as is common with express
// components/routes/webhook.js

module.exports = function(webserver, controller) {

    // Receive post data from fb, this will be the messages you receive
    webserver.post('/facebook/receive', function(req, res) {

        // respond to FB that the webhook has been received.
        res.status(200);
        res.send('ok');

        var bot = controller.spawn({});

        // Now, pass the webhook into be processed
        controller.handleWebhookPayload(req, res, bot);

    });

    // Perform the FB webhook verification handshake with your verify token
    webserver.get('/facebook/receive', function(req, res) {
        if (req.query['hub.mode'] == 'subscribe') {
            if (req.query['hub.verify_token'] == controller.config.verify_token) {
                res.send(req.query['hub.challenge']);
            } else {
                res.send('OK');
            }
        }
    });

}

Once you have created these two files, you will use require and pass your controller into the express module. Your main bot file should look something like this
// bot.js

var Botkit = require('botkit');

// Create the Botkit controller, which controls all instances of the bot.
var controller = Botkit.facebookbot({
    debug: true,
    verify_token: process.env.verify_token,
    access_token: process.env.page_token,
});

// Set up an Express-powered webserver to expose oauth and webhook endpoints
// We are passing the controller object into our express server module
// so we can extend it and process incoming message payloads
var webserver = require(__dirname + '/components/express_webserver.js')(controller);

A: You can find in github a, MIT-licensed, full Demo of running BotKit for Facebook Messenger on an Express server with MongoDB storage.
Here is the main server.js
// modules =================================================
var express = require('express')     // framework d'appli
var app = express()
var bodyParser = require('body-parser') // BodyParser pour POST
var http = require('http').Server(app)      // préparer le serveur web
var dotenv = require('dotenv')
var path = require('path')

// configuration ===========================================

// load environment variables,
// either from .env files (development),
// heroku environment in production, etc...
dotenv.load()

app.use(express.static(path.join(__dirname, '/public')))

// parsing
app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing url encoded

// view engine ejs
app.set('view engine', 'ejs')

// routes
require('./app/routes/routes')(app)

// port for Heroku
app.set('port', (process.env.PORT || 5000))

// START ===================================================
http.listen(app.get('port'), function () {
  console.log('listening on port ' + app.get('port'))
})

A: okay so here goes i was trying the same thing and have been able to start the botkit up with a custom url on express. You dont have to worry about this code at all:
controller.setupWebserver(process.env.port,function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function()     {
  console.log('This bot is online!!!');
 });
});

This repository has its own code with will work with a mongodb database and a express server.
git clone https://github.com/mvaragnat/botkit-messenger-express-demo.git

sudo npm install express --save
sudo npm link body-parser
sudo npm link dotenv
sudo npm install --save botkit
sudo npm install --save monkii
sudo npm install --save mongodb
sudo npm install --save request
sudo npm install --save ejs

In all of the above steps you can perform:
sudo npm link botkit
etc

Finally run node server.js
lt --subdomain botkit --port 5000
restart node server.js

Dont Forget to add your variables to .env file in the directory.
All your traffic on local host will be redirected to the localtunnel, you can get a url using the lt --subdomain name --port 5000
Use this generated url in the webhooks on your page and your bot should be online.


text:
Q: why is constructor called in my WPF when binding? I have a WPF application with the following XAML in my MainWindow.xaml.
I don't understand why the DxTaskList constructor is called when I make a call to OnPropertyChanged("Sequences");. As you see below, my tab control is bound to a Sequences list. In the related view model class, I have a Sequences property that I modify, so naturally I need to let the view know, so I make the call to the OnPropertyChanged("Sequences") but I'm trying to understand how WPF works.
Does the entire visual tree get rebuilt when you refresh the binding of a parent? How does that work? Please note that my app uses Prism, so I'm not sure if this makes a difference.
<dxdo:LayoutPanel Caption="TaskList">
    <dx:DXTabControl x:Name="TabControl"
                     ItemsSource="{Binding Sequences}"
                     SelectionChanged="TabControl_OnSelectionChanged">
        <dx:DXTabControl.View>
            <dx:TabControlMultiLineView HeaderLocation="Bottom"/>
        </dx:DXTabControl.View>
        <dx:DXTabControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <TextBlock Text="{Binding Name}"></TextBlock>
                    <views:DxTaskList x:Name="Tasklst"/>
                </Grid>
            </DataTemplate>
        </dx:DXTabControl.ItemTemplate>
    </dx:DXTabControl>
</dxdo:LayoutPanel>

A: Everything appears to be working as it should.
If your Sequences property is an ObservableCollection it will fire NotifyPropertyChanged on any change to the size of the collection. If Sequences is not an ObservableCollection, but is some other IEnumerable then your OnPropertyChanged("Sequences") will do it.
Back to your question:
Let's assume it is not an ObservableCollection. You insert an item and then fire OnPropertyChanged("Sequences"), a new DxTaskList is created (ctor is called) and gets inserted into the visual tree.
Try calling OnPropertyChanged("Sequences") twice in a row, I bet you are only hitting the constructor after the first, and not on the second. If not, it could be because of how the DxTabControl is internally implemented.


text:
Q: Windows Server 2008 is not showing DHCP-Server configuration in Server-Manager I've successfully installed the DHCP server role on my Windows Server 2008 R2. After configuring everything, DHCP is working just fine.
I can configure the DHCP server via Start -> Programs -> Administration -> DHCP. The problem I'm having is that the configuration of my DHCP doesn't show up in the server-manager.
Any ideas on why it's not showing the sever manager and how I can fix that?

A: Maybe the shortcut was not made when you installed the role, for some reason.
Try typing dhcpmgmt.msc into the Start Menu search box.
It should also be under Roles in Server Manager (ServerManager.msc).


text:
Q: C++ Checking for duplicates in a string I have a function counter(string s1, string s2) which takes two strings (both size 4) of numbers as its parameters. s1 is randomly generated while s2 is user-input.
int counter(string s1, string s2){
    int count = 0;
    int i, j;
    if(i != j){
        for(i = 0; i < 4; i++){
            for(j = 0; j < 4; j++){
                if(s2[i] != s2[j] && s2[j] == s1[i]){
                        count += 1;
                }
            }
        }
    }
    return count;
}

What this function does is compare each element of s2 to s1's. If an element of s2 is equal to an element of s1, provided that they do not have the same index or position, count increments by 1. The function, however, encounters problems when s2 contains duplicates. For example, if s1 = 1234 and s2 = 4445, the output should be 1, but my program outputs 3. How should I be able to detect the duplicates in the string?
Forgot to mention this, but s1 (the randomly generated string) has distinct characters.

A: I dare suggest. But I broke my brain your question =)
int counter(string s1, string s2){
    int count = 0;
    for(int i = 0; i < s1.length(); ++i)
    {
        string::size_type loc = s2.find(s1[i], 0);
        while (loc != string::npos)
        {
           if(loc != i)
               ++count;
           loc = s2.find(s1[i], loc + 1);
        }
    }
    return count;
}

A: add your if condition inside the for loop,
int counter(string s1, string s2){
        int count = 0;
        int i, j;
         for(i = 0; i < 4; i++){
                for(j = 0; j < 4; j++){
                    if(i!=j && s2[j] == s1[i]){
                            count += 1;
                    }
                }
            }
        }
        return count;
    }

A: This would solve the problem you have when the same letter is present in S2 several times.
int counter(string s1, string s2){
    int count = 0;
    int i, j;
        for(i = 0; i < 4; i++){
            for(j = 0; j < 4; j++){
                if(i != j){
                    if(s2[j] == s1[i]){
                            count += 1;
                            break;       // Break out of inner for-loop
                                         // to avoid counting letters twice
                    }
                }
            }
        }
    return count;
}

However, I'm not sure what you want the program to do in case the same letter is present in S1 several times.
EDIT:
After reading some of the clarifications in the comments, the if-statement should be
if(s2[i] != s2[j] && s2[j] == s1[i]){

like in the original post.

A: You can detect duplicate elements by implementing Levenshtein distance algorithms.
 int levenshtein(const char *s, int ls, const char *t, int lt){
    int a, b, c;

    /* if either string is empty, difference is inserting all chars
     * from the other
     */
    if (!ls) return lt;
    if (!lt) return ls;

    /* if last letters are the same, the difference is whatever is
     * required to edit the rest of the strings
     */
    if (s[ls] == t[ls])
            return levenshtein(s, ls - 1, t, lt - 1);

    /* else try:
     *      changing last letter of s to that of t; or
     *      remove last letter of s; or
     *      remove last letter of t,
     * any of which is 1 edit plus editing the rest of the strings
     */
    a = levenshtein(s, ls - 1, t, lt - 1);
    b = levenshtein(s, ls,     t, lt - 1);
    c = levenshtein(s, ls - 1, t, lt    );

    if (a > b) a = b;
    if (a > c) a = c;
    return a + 1;}


text:
Q: Is response to Ajax call different from that of to full postback When I try the following code with a postback the file download takes place normally:
FileInfo file = new FileInfo("C:\\a.txt");
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.TransmitFile(file.FullName);
Response.End();

However if I put the above code inside a public static web method and call it with AJAX I get error, like "Process was being aborted".(Of course to get the current response I write HttpContext.Current.Response) This makes me think that the nature of the two responses are different. My question is if they are different, then what exactly is/are different? Is there a way to achieve the same thing with AJAX?

A: The browser isn't going to receive the file via an XHR (Ajax) call.  You will want to return the file location and then send the browser to that file via window.location or window.open.
Edit: Here's a Web Forms sample.  My Web Forms skills are a little rusty since I've been using MVC now; the syntax is off the top of my head so you might need to fix it up a little.
ASPX Page

    <form id="mikeJMIsAwesome" runat="server">
        <asp:TextBox id="firstName" runat="server" />
        <asp:TextBox id="lastName" runat="server" />

        <asp:Button id="submit" runat="server" />
    </form>

Server Side Code
protected void submit_OnClick(object sender, EventArgs e) {
    //Your logic for creating the file and the code you originally posted for serving the file.
}

A: What Ek0nomik said, file downloads are handled by the browser and cannot be handled through Javascript. The responses are both identical they are are both just http responses - you can verify this with fiddler or another tool (http://www.fiddler2.com/fiddler2/).
Essentially you ajax method will not be able to handle receiving a file and will certainly not have the permissions to assemble it and store it on you hard drive.
You can 'fake' a user clicking on a link using some Javascript.
Please check this similar question for an answer. I've pasted the answer from it below.
starting file download with JavaScript
We do it that way: First add this script.

Place this where you want the download button(here we use just a link):

<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download
The file 'download.php' (needs to be put on your server) simply contains:

<?php
   header("Content-Type: application/octet-stream");
   header("Content-Disposition: attachment; filename=".$_GET['path']);
   readfile($_GET['path']);
?>

So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter. We think this is the best solution!


text:
Q: jQuery Mmenu mobile issue I'm currently working on a responsive website. I'm using jQuery MMenu for the menu and it's working perfectly in all desktop resolutions expect when I see the website in a smartphone.
The submenu is not displayed correctly. As you can see in the image link below when I open the submenu the last item is part of the first menu.
http://i.imgur.com/haYVWhT.png?1
I don't know why is this happening, have this ever occurred to you?
Thanks in advance.


text:
Q: Loading images from a URL for a material texture with Swift I'm trying to create a custom material from a remote image to add to a ModelEntity with RealityKit. Works totally fine with a local image but trying anything remote I get a loading error.

Fatal error: 'try!' expression unexpectedly raised an error: RealityKit.TextureResource.(unknown context at $1b9817f08).LoadError.importFailureWithURL(https://upload.wikimedia.org/wikipedia/commons/1/1b/Demetrius_III_bust.png)

I've tried multiple images from different source, both http, https, .png, .jpg. Can't find a working example of this anywhere. If it matters the the id I'm passing to withName is a UUID.
func createMaterial(id: String, imageURL: String) -> Material{
        var material = SimpleMaterial()
        material.metallic = MaterialScalarParameter(floatLiteral: 0.0)
        material.roughness = MaterialScalarParameter(floatLiteral: 1.0)
        let texture: TextureResource = try! TextureResource.load(contentsOf: URL(string:imageURL)!, withName: id)

        let materialTexture: MaterialColorParameter = MaterialColorParameter.texture(texture)
        material.baseColor = materialTexture
        return material
 }

PS If anyone can recommend a good library to handle loading and caching images for this sort of use case that would be a huge help. Everything I've found seems targeted towards UIImages or SwiftUI Images.
Update 1: Here is the full error after wrapping the lines in a catch:

[API] URL passed to REAssetManagerTextureNoNetworkSyncMemoryAssetCreateWithURL must be a file URL: https://upload.wikimedia.org/wikipedia/commons/1/1b/Demetrius_III_bust.png
Failed to import entity from "https://upload.wikimedia.org/wikipedia/commons/1/1b/Demetrius_III_bust.png"

I also update my Info.plist's App Transport Security Settings to Allow Arbitrary Loads

A: Looks like the contentsOf parameter of TextureResource.load() requires an internal file URL not an external URL. I solved this in my case by manually downloading the images I needed first.


text:
Q: add one mean trend line for different lines in one plot i'm trying to add a trend line (linear mean) to a plot. I want to have one mean trend line for 11 seperate lines in one plot. My plot looks like that:

Now i want to have one (1) mean trend for the coloured lines . The two grey lines are max and min values, that shell not be considered when forming the mean trend line. Only trend line for the coloured lines. My data looks like that:
jahr    beob    werex_00    werex_11    werex_22    werex_33    werex_44    werex_55    werex_66    werex_77    werex_88    werex_99    Min Max
1961    NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  -18,6304    61,1809
1962    NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  -11,9439    87,5546
1963    NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  -15,5266    82,2700
1964    NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  -40,0319    85,2906
1965    NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  -34,3038    94,9024
1966    -3,8771 8,3257  24,8513 13,5184 21,0853 15,6732 1,8496  -8,4903 2,1629  8,2024  16,1356 -31,3819    92,7969
1967    -9,4982 11,3976 23,0892 13,9196 16,8335 17,2100 2,9570  -10,1167    3,9671  7,2876  10,6471 -7,5067 110,6196
1968    -11,2913    11,4993 18,3050 8,0152  13,9073 16,8016 4,7250  -12,9246    2,6713  5,4357  3,5107  -51,2107    138,7448
1969    2,6362  9,1087  19,9564 6,0345  3,8747  11,6780 2,5116  -13,4089    4,3353  0,3998  3,1798  -30,3322    42,1300
1970    6,6531  2,0238  20,5422 2,3972  0,4017  11,1036 5,0465  -10,2958    8,3485  -2,1658 4,6128  -11,5068    44,3986
1971    -1,7923 3,0214  18,7542 2,5401  -2,5444 8,3054  1,8535  -10,1233    8,3663  2,0204  1,9454  -22,3762    95,3033
1972    -1,1383 0,1923  21,6838 -1,2288 -4,1658 4,4113  2,5008  -7,6908 9,6488  2,3338  0,7093  -29,0978    31,1931
1973    -3,9827 2,7288  19,6430 -0,1119 -3,9149 3,1060  -3,5426 -5,1332 3,9206  1,2295  -6,9931 -30,3709    44,2175
1974    -5,6800 -0,2600 13,2311 1,2855  -11,7234    -8,2399 -5,7620 -4,3448 8,3248  -0,5500 -5,6376 -44,4719    143,3977
1975    -0,6020 4,4594  13,4312 1,8103  -11,7964    -11,2020    -2,9454 -0,8192 6,8733  -1,6069 -7,5460 -27,5719    46,5896
1976    9,0707  4,0255  12,8539 0,5613  -9,0911 -14,6242    -2,0957 0,3028  4,2881  -4,2491 -1,5111 -36,0912    22,2878
1977    6,2822  7,5568  3,2908  1,3875  -9,0588 -14,0812    -2,3505 2,0262  2,7041  -1,6706 2,6180  -13,8766    99,9908
1978    8,9476  11,4753 -0,1546 0,4597  -7,2769 -9,6268 -0,7031 1,2291  -0,2699 -2,7092 3,2059  -19,4729    79,3319
1979    8,9790  6,8742  -3,7599 -1,0170 -4,2174 -11,7519    -2,6872 4,4382  0,2518  -3,8938 4,6531  -39,0920    78,4498
1980    -0,7982 5,3090  -7,1990 0,3482  0,7074  -3,8802 -1,6347 5,7365  -2,5424 -4,5144 4,2867  -43,8048    95,6593

.....
now i plottet the date after using melt() for ggplot.
Melting transforms data to:
Jahr    Projektion  value
1961    beob    NA
1962    beob    NA
1963    beob    NA
1964    beob    NA
1965    beob    NA
1966    beob    -3,877072807
1967    beob    -9,498158353
1968    beob    -11,29127163
1969    beob    2,636225556
…   …   …
1961    werex_00    NA
1962    werex_00    NA
1963    werex_00    NA
1964    werex_00    NA
1965    werex_00    NA
1966    werex_00    8,32566516
1967    werex_00    11,39762871
1968    werex_00    11,49932052
1969    werex_00    9,108708251
…   …   …

Now i plotted the data (pic above):
Projektionen_Farben<-c("#000000","#00EEEE","#EEAD0E","#006400","#BDB76B","#EE7600","#68228B","#8B0000","#1E90FF","#EE6363","#556B2F","#D6D6D6","#D6D6D6")
GJm11_Grundwasserneubildung_Jahr_norm_druckreif <- melt(GJm11_Grundwasserneubildung_Jahr_norm,na.rm = FALSE, id.vars="jahr")
names(GJm11_Grundwasserneubildung_Jahr_norm_druckreif)<-c("Jahr","Projektion","value")
GJm11_Grundwasserneubildung_Jahr_norm_druckreif$Jahr <- as.numeric(factor(Jahr))
ggplot(GJm11_Grundwasserneubildung_Jahr_norm_druckreif,aes(x=Jahr,y=value,color=Projektion,group=Projektion))+
  geom_line(size=0.8) + xlab("Jahr") + ylab("Grundwasserneubildung [mm/a]") +
  ggtitle("Grundwasserneubildung") +  theme_bw() +
  scale_x_continuous(breaks=c(1961,1980,2000,2020,2040,2060,2080,2100)) +
  theme(axis.title=element_text(size=15,vjust = 0.3,face="bold"), title=element_text(size=15,vjust = 1.5,face="bold")) +
  scale_colour_manual(values = Projektionen_Farben) + coord_cartesian(xlim = c(1961, 2100)) +
  geom_ribbon(data=GJm11_Grundwasserneubildung_Jahr_norm,aes(x=jahr,ymin=Min,ymax=Max),inherit.aes=FALSE,alpha=0.1,color="grey30")

So how can i get the mean trend line for the coloured lines?
Also i wolud like to know, if there is a way to add mean trend lines for certain time periods like 1961-2000, 2021-2050 and 2071-2100 as well, just to compare trend for this time periods?
Hope somebody can give me a hint.

A: If you want to add a trend line I would consider to not plot them on top of the actual data, because you might not be able to see it. Instead, I would just add a geom_smooth:
 + stat_smooth( aes( y = value, x = jahr), inherit.aes = FALSE )

If you want to color different time periods you could do something like:
GJm11_Grundwasserneubildung_Jahr_norm_druckreif$decade <- as.factor( trunc((GJm11_Grundwasserneubildung_Jahr_norm_druckreif$Jahr -1900) / 10, digits=0) )

and add
+ stat_smooth( aes( y = value, x = jahr, color= decade), inherit.aes = FALSE )

instead to your plot.

A: you can use stat_summary
last_plot() + stat_summary(fun.y=mean, geom="line")


text:
Q: Conversion from MQTT to AMQP/STOMP I'm kind of new to these protocols, and just started exploring Message brokers like Apache Apollo and RabbitMQ.
So my broker receives MQTT messages from a publisher. And I would like to convert it into AMQP (preferably) or STOMP protocol to send to a web server. But I've so far been unable to do so.
I looked into RabbitMQ, and tried enabling the MQTT plugin, but when I do load it, I'm unable to start the server.
I was wondering if anyone can guide me here? Is there an API that can help me? And I'm very confused about RabbitMQ. I've been able to load other plugins easily,like stomp, management utilities etc.

A: I'm 100% sure it is doable. I am doing it right now with robomq.io broker. One cause could be sometimes bugs in your client library restrict you doing so.
Another thing you should be aware of is that internally, RabbitMQ MQTT adapter is mapped into amq.topic exchange by default, so on your STOMP peer, you should subscribe or send to /topic/yourTopic; on your AMQP peer, bind your queue to amq.topic exchange or publish to that exchange.
Follow this example code and documentation to build your client.
If you can't figure out your server, just get a free trial from robomq.io. It saves you time and money.
The development tool I am using is robomq.io broker, producers in Python (AMQP library: pika, MQTT library: paho, STOMP library: stompest), consumer in Node.js (library: amqplib).
Hope it helps!

A: Well, I'm not sure if this question should be taken down. But if it has to be I leave it to the discretion of the moderators and the stackOverflow community in general.
btw, I use Ubuntu 14.04.
About the RabbitMQ broker
So Mosquitto was running un the background occupying the port 1883 normally used for MQTT. I could have changed the port for RabbitMQ, but decided against it and tried to kill the Mosquitto process. But for some reason, I could NOT.
For now, my quick fix was removing Mosquitto completely and this freed the port, enabling RabbitMQ to use it.
About the protocols
I've used Paho and the RabbitMQ libraries provided to code out simple programs that can publish and receive messages in AMQP/MQTT via the RabbitMQ broker.
(My Googling needs to be better!)
Still haven't converted one to the other. But that shouldn't be too big a step to achieve.
Still would be nice to know if there's an API or something that can help me achieve the conversion in a very simple manner. Of course, if there's not, I'll figure it out ASAP
Any suggestions/comments are heartily welcome. I'm brand new to all this and could really use advice from all you seasoned pros :)


text:
Q: vimrc help : trying to map Ctrl-s to :w My current .vimrc file is
syntax on
colorscheme zellner
set nu
set ruler
set si "Smart indet
map <C-s> :w<cr>

I thought the last line would allow me to hit control-s to automatically save while in normal mode?
{
The last line is just the trim downed version of what I really want which is
map <C-s> <esc>:w<cr>a

}
Am I forgetting something?
I'm using vim 7.3 that came with my mac.

A: Like mentioned if you want it on both modes you have to just put
inoremap <C-s> <esc>:w<cr>a
nnoremap <C-s> :w<cr>a

in your .vimrc.
But note that if you are using the terminal vim then you might have a problem
mapping ctrl-s. By default it stops the flow. In that case add the following to your .bashrc (not sure if the same problem in zsh):
stty -ixon

A: If I got it right, you want
:inoremap <C-s> <esc>:w<cr>a

Whoops, just read you want it in normal mode
:nnoremap <C-s> :w<cr>

When you're writing commands in vim files (like .vimrc) you don't need the :. It is only a method of entering commands on the command line.


text:
Q: How can I compare column data with a String in GridView I need to hide content of a column based on comparing its data with a string. I like to do it in Page itself (Page does not have code behind)
For some reason I cannot use Eval or Bind to retrieve data for column. I'm looking for something like,
<asp:GridView  ID="GridView1" runat="server" >
  <Columns>
    <asp:TemplateField>
      <%
        if ([data from row] == aVarContainingDataToCompare){
          Response.Write("Hidden");
        } else {
          Response.Write([data from row]);
        }
      %>
    </asp:TemplateField>
    <asp:TemplateField>
      <ItemTemplate><%# Eval("AnotherData") %></ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

Can I do this without using code behind

A: Is it alright to use following instead? Please note the # sign at the start
<asp:GridView ID="GridView1" runat="server">
   <Columns>
     <asp:TemplateField>
       <%# (Eval("TheColumn").ToString() == aVarContainingDataToCompare ? "Hidden": Eval("TheColumn")) %>
     </asp:TemplateField>
       ...
   </Columns>
 </asp:GridView>


text:
Q: Select and Delete multiple rows by selecting checkboxes using PHP Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database  using below code problem is iam having problem with php script
 <input class='file'  type="checkbox" class="form-control" name="hid" id="<?php $rs["carimgid"]; ?>" placeholder="Please choose your image">

this my ajax script where using this to delete multiple row without refresh
<script type="text/javascript">
$(document).ready(function(){
    jQuery('#master').on('click', function(e) {
        if($(this).is(':checked',true))
        {
            $(".sub_chk").prop('checked', true);
        }
        else
        {
            $(".sub_chk").prop('checked',false);
        }
    });
    jQuery('.delete_all').on('click', function(e) {
        var allVals = [];
        $(".sub_chk:checked").each(function() {
            allVals.push($(this).attr('data-id'));
        });
        //alert(allVals.length); return false;
        if(allVals.length <=0)
        {
            alert("Please select row.");
        }
        else {
            //$("#loading").show();
            WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
            var check = confirm(WRN_PROFILE_DELETE);
            if(check == true){
                //for server side

                var join_selected_values = allVals.join(",");

                $.ajax({

                    type: "POST",
                    url: "delete.php",
                    cache:false,
                    data: 'ids='+join_selected_values,
                    success: function(response)
                    {
                        $("#loading").hide();
                        $("#msgdiv").html(response);
                        //referesh table
                    }
                });
              //for client side
              $.each(allVals, function( index, value ) {
                  $('table tr').filter("[data-row-id='" + value + "']").remove();
              });

            }
        }
    });
    jQuery('.remove-row').on('click', function(e) {
        WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
            var check = confirm(WRN_PROFILE_DELETE);
            if(check == true){
                $('table tr').filter("[data-row-id='" + $(this).attr('data-id') + "']").remove();
            }
    });
});
</script>

and my php code is
<?php
  include("config.php");
   if(isset($_POST['ids'])){

 $result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid ='$id'");
   }
?>

Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database  using below code problem is iam having problem with php script

A: You haven't got the ids from POST.
Look at the following
$ids = mysqli_real_escape_string($con, $_POST['ids']);
if(!empty($ids)){
    $result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid IN ({$ids})");
}


text:
Q: Titanium: How to reload a tab upon focus? I have built a favorite-tab in my application that displays entries in a database that  are flagged as such. On the backside this works as it should, but I can't figure out how to reload the favorites tab after changes have been made. When I quit and relaunch the app though, the updates appear as they should.
In essence I have the same problem as is presented here: http://developer.appcelerator.com/question/31211/tab---tableview--database-reload

"I have a 'search' and 'search history' tab in my application. Every search executed under this tab gets inserted into my local db.
    However the new search is not reflected in the tableview retrieving data from the DB in the 'search history' tab when i browse to it, after searching.
    The latest search, however, gets loaded when I exit the app and relaunch it.
    I need some help in figuring out how to trigger the tableview reload without exiting the app.
    SOLUTION UPDATE:
    I feel 'noobish' for asking this question but it was really so simple
    I added a 'focus' eventlistener for the window housing the tab to load the data.
    win.addEventListener('focus', function() { loadDBdata(); });

This seems reasonable, but what should the loadDBdata function should contain?
I would greatly appreciate any pointers to this.

A: i would suggest firing an event when the favorites are updated and having an event listenter on the table that holds the favorites list. When it receives the event, it should update the tables contents.
see this question I just answered it should provide a guide for solving your problem also
Problems with refresh function for page, in Appcelerator

A: the loaddb function should contain something like:
// init database
var db = Ti.Database.install('path/to/database.db','myDB');

// your request
var sql = 'SELECT * FROM myDatabaseTable';

// the result from that request
var myContent = db.execute(sql);

// need to put the result in a valid structure before inserting into your tableview
var data = [];
while (myContent.isValidRow()){
  // your tableviewrow
  var row = {
    title = myContent.field(0);
  };
  data.push(row);
  myContent.next();
};

// need to close stuff (!)
myContent.close();
db.close();

// finally return data
return data;


text:
Q: Proving that $\frac{\text{d}\vec{v}}{\text{dt}}=\frac{\text{d}|\vec{v}|}{\text{dt}}\hat{v}+\frac{\text{d}\hat{v}}{\text{dt}}|\vec{v}|$. We were taught the following equation on a physics lecture:
$$\frac{\text{d}\vec{v}}{\text{d}t}=\frac{\text{d}|\vec{v}|}{\text{d}t}\hat{v}+\frac{\text{d}\hat{v}}{\text{d}t}|\vec{v}|$$
where $\vec{v}$ is a velocity vector dependent on time $t$. I was wondering how the equation could be proven.

A: For scalar $\phi$ and vector $A$,$$\frac{\text{d}}{\text{d}t}(\phi A_i)=\frac{\text{d}\phi}{\text{d}t}A_i+\frac{\text{d}A_i}{\text{d}t}\phi\implies\frac{\text{d}}{\text{d}t}(\phi A)=\frac{\text{d}\phi}{\text{d}t}A+\frac{\text{d}A}{\text{d}t}\phi,$$by contraction with the standard basis $e^i$. Now take $\phi:=|v|,\,A:=\hat{v}$.

A: Just write
$$
\vec{v} = |\vec{v}| \hat{v} \tag{1}
$$
that is to say: vector $\vec{v}$ is of magnitude $|\vec{v}|$ and pointing in the direction $\hat{u}$. After that, apply the product rule on Eq. (1)

A: If $\hat{v}$ is the unit vector with the same direction as $v$, then this should be true by the fact that
$$
\vec{v}=|\vec{v}|\hat{v}
$$
and by using the product rule for derivative.


text:
Q: VS 2003 and SourceSafe How to Add .vbproj.webinfo file to sourcesafe How to add .vbproj.webinfo file to sourcesafe? and
This is my local folder:

I want to add That file to sourcesafe.
But no option from visual studio to access that file.

Please help


text:
Q: Parsing CoNLL-U missing annotation (misc) I'm trying to parse .ConLL files from this github Repo, an example of my parsing code:
from io import open
from conllu import parse_tree_incr
import glob
import os

for filename in glob.glob('./licenses-conll-format/22-MIT/MIT_permissionCopy.conll'):
    data_file=open(filename, "r", encoding="utf-8")
    for tokentree in parse_incr(data_file):
        print(tokentree.serialize())

output :
24  Permission  _   NN  NN  _   27  nsubjpass   _   _
25  is  _   VBZ VBZ _   27  auxpass _   _
26  hereby  _   RB  RB  _   27  advmod  _   _
27  granted _   VBN VBN _   11  rcmod   _   _
28  ,   _   ,   ,   _   27  punct   _   _
29  free    _   JJ  JJ  _   27  advmod  _   _
30  of  _   IN  IN  _   0   erased  _   _
31  charge  _   NN  NN  _   29  prep_of _   _

this seems to be missing some annotations (I-PERMISSION,B-PERMISSION etc ..) from the original .conll file :
24  Permission  _   NN  NN  _   27  nsubjpass   _   _   B-PERMISSION    COPY
25  is  _   VBZ VBZ _   27  auxpass _   _   I-PERMISSION
26  hereby  _   RB  RB  _   27  advmod  _   _   I-PERMISSION
27  granted _   VBN VBN _   11  rcmod   _   _   I-PERMISSION
28  ,   _   ,   ,   _   27  punct   _   _   O
29  free    _   JJ  JJ  _   27  advmod  _   _   I-PERMISSION
30  of  _   IN  IN  _   0   erased  _   _   I-PERMISSION
31  charge  _   NN  NN  _   29  prep_of _   _   I-PERMISSION
32  ,   _   ,   ,   _   27  punct   _   _   O

Any thoughts on how to get all the annotations ?

A: You can specify the tuple of fields yourself:
fields = ('id', 'form', 'lemma', 'upostag', 'xpostag', 'feats', 'head', 'deprel', 'deps', 'misc', 'rest')
for tokentree in parse_incr(data_file, fields=fields):
    print(tokentree.serialize())

output:
24  Permission  _   NN  NN  _   27  nsubjpass   _   _   B-PERMISSION
25  is  _   VBZ VBZ _   27  auxpass _   _   I-PERMISSION
26  hereby  _   RB  RB  _   27  advmod  _   _   I-PERMISSION
27  granted _   VBN VBN _   11  rcmod   _   _   I-PERMISSION


text:
Q: Smoothing property of the Schrodinger equation It is well known that the heat diffusion equation
$$ u_t - u_{xx} = 0  ,\quad u(0, x ) = f(x) , $$
has the smoothing property.
The question is, how about the imaginary equivalent of it, namely the Schrodinger equation?
$$ i u_t = u_{xx} ,\quad u(0, x ) = f(x) .  $$
If the initial state $f$ is not derivative at some point, is this property retained by the solution $u$?


text:
Q: Openstack API server URL Openstack offers many well-documented RESTful APIs for request-based programming. However, I couldn't find any information on what URL I should send the HTTP requests for each API. Where am I supposed to send the requests to? Do I need to set up a server myself? How am I supposed to do that? I have a fully operational Openstack running on a local cluster and I can run commands with the CLIs normally.
These questions seem so silly they're not even answered clearly in the docs.

A: The API endpoints should be viewable through Horizon + the CLI. In Horizon you'll find this information under "Access and Security" > "API Access."
Through the CLI you can find the information via the OpenStack or Keystone client. The client you will use depends on which version of OpenStack you are using. If you are using a newer version then you will probably operate through the OpenStack client.

openstack endpoint list --long

or

keystone endpoint-list

After you get the URLs you should be able to curl them, however they will require authentication. You'll need to auth/get a token from Keystone.

A: Answer by Michael will work, but in case you don't wanna use CLI then login into the horizon dashboard and access the access and security option. This will list all the base Api urls for Openstack Api's.

*image source: link


text:
Q: Fire an Outlook 2003 macro when the user creates a new blank message I found events that fire when the user receives a message, or hits the send button, but nothing that fire when the user creates a blank, new email.

A: You should be able to use the NewInspector event.  Example:
Public WithEvents myOlInspectors As Outlook.Inspectors

Private Sub Application_Startup()
    Initialize_handler
End Sub

Public Sub Initialize_handler()
    Set myOlInspectors = Application.Inspectors
End Sub

Private Sub myOlInspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
    Dim msg As Outlook.MailItem
    If Inspector.CurrentItem.Class = olMail Then
        Set msg = Inspector.CurrentItem

        If msg.Size = 0 Then
            MsgBox "New message"
        End If
    End If
End Sub


text:
Q: Registry Value Access I have been trying to work out why I can not access a value in the registry.  I ended up with a possible solution but I would like to know why one works and the other doesn't and if I can go ahead and use this solution.
The original code:
RegistryKey regKey1 = Registry.LocalMachine.OpenSubKey(regPath);
string regValue1 = (string)regKey1.GetValue("CodeBase");

This fails because regKey1 is null.
A possible replacement (this works):
string regValue2 = (string)Registry.GetValue(Registry.LocalMachine.Name + regPath, "CodeBase", String.Empty);

According to this post there should be a different way of accessing the registry if the program is compiled for 32-bit and is running on a 64-bit machine.  I am using a 64-bit version of Windows 7 and the program is being compiled for 'Any CPU'.  However, if this was the reason then I would expect both solutions above to fail.
Can someone please explain the difference?
EDIT:
Found the problem.
regPath = @"\SOFTWARE\Wow6432Node\Classes\CLSID\ ...";

Because of the comment by David Heffernan I changed Registry.LocalMachine.Name + regPath into Path.Combine(Registry.LocalMachine.Name, regPath), but this didn't work to start with because regPath started with a '\' (the items were not combined - without an exception).  Then I realized that OpenSubKey() also doesn't like the '\' at the start.  After removing this from regPath both versions work the same.  Thanks David and thanks also for your suggestions about using the RegistryView enum.

A: Version 1
If the key does not exist then regKey1 is null, and the call to regKey1.GetValue() fails for the obvious reason.
Version 2
If the key does not exist, Registry.GetValue() returns null, and regValue1 is therefore assigned null.

Regarding the issue of registry views and AnyCPU, you are asking for trouble at present. Presumably you mean to look in a specific registry view. You should be explicit about this by using the RegistryView enumeration.


text:
Q: Motor pump slowed down due to suction blockage I have a 1 HP, 220V motor pump which was working fine till recently. Last day, some dirt and dried leaves got into the foot valve and blocked the suction pipe. I ran the pump for sometime in that condition. After a few minutes my MCB tripped off indicating a short circuit. The motor casing appeared to be unusually hot. Thereafter, when  i turn on the pump, its running at a very slow speed and not sucking water. After a few 30 seconds it gets hot and my MCB would trip off. I have no clues what is happening. Can somebody tell me if my coil would have burned off? I am not sure what kind of motor it is using.

A: All 220v water pumps I've worked with to date used induction motors. Assuming this is the case with your motor, the slower the spindle speed, the more current flows through the motor, thus explaining both the case heating and the MCB tripping (an induction motor whose spindle is stopped from moving at all effectively appears as a "dead short" to the input power supply). As for the slower operation after the initial overload problem, you may have damaged the motor start/run capacitor, or overheated/damaged a bearing or seal, causing a loss of efficiency/increase in drag, causing the now too slow speed & the resulting continued overcurrent & heating problems.


text:
Q: How to set width from tinyMCE in Wicket Cant set any width from tinyMCE3 in Wicket. I already used google :D
but with no result. How can i control the size from tinyMCE?
final TextArea<String> textTextField = new TextArea<String>("text");
textTextField.setLabel(new StringResourceModel("text.module.edit.text", TextModuleEditPanel.this));
textTextField.setRequired(true);

final TinyMCESettings settings = new
TinyMCESettings(TinyMCESettings.Theme.advanced);
// Some other settings

settings.addCustomSetting("cleanup : false");
settings.addCustomSetting("verify_html : false");
settings.addCustomSetting("plugins: 'autoresize'");
settings.setResizing(Boolean.TRUE);

TinyMceBehavior tinyMceBehavior = new TinyMceBehavior(settings);

textTextField.add(tinyMceBehavior);

form.add(textTextField);

A: Try with:
settings.addCustomSetting("width : '500'");
settings.addCustomSetting("height : '300'");

According to https://stackoverflow.com/a/4145058/497381 this is how TinyMCE 3 should be initialized.


text:
Q: How to create three columns in navigation submenu I was able to successfully create a navigation menu with a submenu that appears on hover. However, I would like my submenus to have columns. I used Vanga Sasidhar's tips on creating the hover nav, I now need to create the columns under the Solutions and Support menu items.
Here is my jsfiddle: http://jsfiddle.net/DKu7p/.
Here is my CSS:
.site-nav li {
display:block;
float:left;
list-style:none;
margin: 0;
position: relative;
width: 100px;
}

.site-nav li:hover {
background:#1f78c3;
cursor:pointer;
}
.site-nav li a {
color:#696969;
display:block;
text-align:center;
text-decoration:none;
padding:5px 10px;
}

.site-nav li a:hover {
color:#00598B;
display:block;
text-align:center;
text-decoration:none;
padding:5px 10px;
}

.site-nav .dropdown {
    display : none;
    position : relative;
}
.site-nav .dropdown li { float : none; }
.site-nav li:hover .dropdown { display : block; position: relative; }

.dropdown {
background: #fff;
border: 1px solid #fff;
border-top: 0;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
list-style: none;
margin: 4px 0 0 -9px;
min-width: 150px;
overflow: hidden;
padding: 0;
position: relative;
z-index: 999;
}
.dropdown li {
border: 0;
border-radius: 0;
clear: both;
float: none;
font-size: .9em;
margin: 0;
width: 100%;
}
.dropdown li span {
display: none !important;
}
.dropdown li a {
background: none;
color: #333;
display: block;
font-size: 1.1em;
font-weight: normal;
padding: 5px 8px;
text-align: left;
text-shadow: none;
 }
.dropdown li a:hover {
background: #ddd;
color: #0c84bb;
text-decoration: none;
}

.dropdown .last a {
border-bottom: none;
}

A: Ok, here my try:
Apply the three column css layout
.col-columned{
    width: 450px;
}
.col-maincontainer{
width: 450px; /*Width of main container*/
margin: 0 auto; /*Center container on page*/
}
.col-maincontainer ul, .col-maincontainer ul{
    margin: 0;
    padding: 0;
    list-style-type: none;
}
.col-contentwrapper{
float: left;
width: 100%;
}

.col-contentcolumn{
margin: 0 190px 0 180px; /*Margins for content column. Should be "0 RightColumnWidth 0 LeftColumnWidth*/
}

.col-leftcolumn{
float: left;
width: 150px; /*Width of left column in pixel*/
margin-left: -450px; /*Set margin to that of -(MainContainerWidth)*/
background: #C8FC98;
}

.col-rightcolumn{
float: left;
width: 150px; /*Width of right column*/
margin-left: -150px; /*Set left margin to -(RightColumnWidth)*/
background: #FDE95E;
}

.col-innertube{
margin: 3px; /*Margins for inner DIV inside each column (to provide padding)*/
margin-top: 0;
}

And then, add a new element with the html markout of three columns:
Example1

topic1

topic2

topic3

topic1

topic2

topic3

topic1

topic2

topic3

Make sure to add the col-columned to the dropdown element like this:

Here the live example:  http://jsfiddle.net/8fgG5/1/


text:
Q: bootstrap template refusing to be responsive on mobile phones I'm having strugle with getting my Bootstrap website to be responsive, basicly its responsive on iPad and bigger devices, but on mobile phones the contest "dissapears" and changes font/size of elements to bootstrap default ones. I checked all CSS links (bootstrap main CSS, JS etc) and they are all on place and properly positioned in html file. I want to mention that I properly used bootstrap grid system, I don't know why it refuses to be responsive on mobile phone.
https://jsfiddle.net/hbb1sLut/7/
live : http://i1cevic.com
html
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1 maximum-  scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>test</title>

<link href="css/style.css" rel="stylesheet">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/bootstrap.min.css">

<link rel="stylesheet"  href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Raleway:200,300,400" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic' rel='stylesheet' type='text/css'></title>

First Line
Second Line

            RANDOM CTA

Test   Test

lorem ipsum

Test

Lipsum

Test

Lipsum

Test

Lipsum

   </script>

css
/* Global Styles */

html,
body {

width: 100%;
height: 100%;
     }

a:hover,
a:focus {
text-decoration: none;
outline: none;
    }

a {
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
-ms-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}

#FullScreen {
position: relative;
display:table;
color: #fff;
width:100%;
height:100%;
background-image: url(../img/bg.jpg);
background-size:cover;
background-position:center bottom;

            }

#section1 {

padding-top:90px;
padding-bottom:90px;

          }

/* Vertical + Horizontal Center */

.home-container {
display: table-cell;
text-align:center;
vertical-align: middle;
                }

/* Typography */

.bold {
font-weight:bold;
      }

p {

font-family: 'Raleway', sans-serif;
font-weight: 300;
font-size: 14px;
color:#787878;
line-height:25px;

  }

h5 {
font-family: 'Raleway', sans-serif;
font-weight: 300;
font-size: 18px;
letter-spacing:normal;
color:#787878;

   }

h4 {
font-family: 'Raleway', sans-serif;
font-weight: 100;
font-size: 46px;
letter-spacing:-1px;
line-height:30%;

}

h3 {
font-family: 'Montserrat', sans-serif;
font-weight: 400;
font-size: 20px;
letter-spacing:-0.5px;
color:black;
   }

A: I'm not sure what you mean by contest
But I tested your live site on different sized screens and nothing disappears, it works as expected

A: Edit the live code (uploaded at http://i1cevic.com/) to include the CDN bootstrap link instead of your own downloaded one.
Always try and use CDNs.
Hope this helps solve the issue


text:
Q: How do I undo the patch to openvpn recommended by Private Tunnel? i was making new connection with openvpn by documents on privatetunnel.com and at the end of docs i enter this command in terminal and after that openvpn in broken. i remove open vpn with apt-get remove openvpn and one  time with purge command after that i install again openvpn but it's not available in creation of new connection.
the code i entered and everything gone wrong is this:
mv /usr/sbin/openvpn /usr/local/sbin; echo -e '#!/bin/bash\n/usr/local/sbin/openvpn $* --ns-cert-type server &\ntrap "kill $!" EXIT\nwait $!\n' > /usr/sbin/openvpn; chmod +x /usr/sbin/openvpn

i just want undo this command.

A: I think you overwrote /usr/sbin/openvpn (the openvpn binary). Can you show me the output of:
# file /usr/sbin/openvpn

A: To undo the specific command you included in the question post, run:
sudo mv /usr/local/sbin/openvpn /usr/sbin/

Explanation:
The original command moved the file openvpn from /usr/sbin/ to /usr/local/sbin/, and then it created a script called openvpn in /usr/sbin/. To undo this, we need to move the original file /usr/local/sbin/openvpn to /usr/sbin/, overwriting the script.


text:
Q: About pinned memory in CUDA, is there an upper limit on it? I wrote an application that would be benefit from pinned memory, and the best performance can be achieved when there are fairly large pinned memory.
We ordered a server, consisting of 768GB memory and I plan to allocate ~500GB memory as pinned, is there any problem with that, since I have never allocated that much pinned memory before, so far on our servers with much smaller memory installed, I dont see any problem of allocating large chunk of memory as page-locked/pinned.
The targetting OS of my application will be both Windows server 2008 R2 and RHEL6+, CUDA version being 6.0 RC or 5.5, GPUs are tesla K20x, btw.

A: There is no maximum pinned memory limit in CUDA. It is determined by the amount of main memory your machine have, the memory required by other process(OSs and applications) etc.
Sometimes, the OS puts a limit on the maximum amount of page-locked memory any process can request which has a soft limit and a hard limit. You can change the both.


text:
Q: como llamo una funcion dentro de otra funcion kotlin tengo las 3 siguientes funciones que quisiera llamar en una sola función en kotlin: para escribir un solo numero y que me evalué las 3, dejo mis códigos. ósea crear una 4ta funcion que llame alas otras 3 por ejemplo  la funcion fun llamadaAtodasLasFunciones me sirva para llamar a las otras, como se le darian los parametros, gracias soy nuevo en esto de kotlin
fun llamadaAtodasLasFunciones(no se como llamarlas :( ) {
}

fun meses2021(mesesCorrientes : Int) {
    when(mesesCorrientes){
    1 -> println("Enero")
    2 -> println("Febrero")
    3 -> println("Marzo")
    4 -> println("Abril")
    5-> println("Mayo")
    6 -> println("Junio")
    7 -> println("Julio")
    8-> println("Agosto")
    9-> println("Septiembre")
    10 -> println("Octubre")
    11 -> println("Noviembre")
    12 -> println("Diciembre")
    else -> {
    println("No esta dentro de los meses del año")

}
}
}

fun apuntarMese(apuntar : Int) {
    when(apuntar) {
    1,2,3,4 -> println("corresponde al primer cuatrimestre")
    5,6,7,8 -> println("corresponde al segundo cuatrimestre")
    9,10,11,12 -> println("corresponde al tercer cuatrimestre")
    else -> { println("No esta dentro de los meses del año")
    }
}
}

fun mesesRango(mes: Int) {
when(mes) {
    in 1..6 ->println("Primer semestres del año")
    in 7..12 ->println("Segundo  semestres del año")
    !in 1..12 ->println("No corresponde a los meses que necesita")
    }
}

A: No sé si esta sea la respuesta que buscas pero puedes simplemente llamarlas una por una
fun llamadaAtodasLasFunciones(mes: Int) {
    meses2021(mes)
    apuntarMese(mes)
    mesesRango(mes)
}

Por cierto, si en todos los casos vas a a imprimir algo, te conviene sacar el println afuera del when para no tener que repetirlo:
fun meses2021(mesesCorrientes: Int) = println(
    when (mesesCorrientes) {
        1 -> "Enero"
        2 -> "Febrero"
        3 -> "Marzo"
        4 -> "Abril"
        5 -> "Mayo"
        6 -> "Junio"
        7 -> "Julio"
        8 -> "Agosto"
        9 -> "Septiembre"
        10 -> "Octubre"
        11 -> "Noviembre"
        12 -> "Diciembre"
        else -> "No esta dentro de los meses del año"
    }
)

fun apuntarMese(apuntar: Int) = println(
    when (apuntar) {
        1, 2, 3, 4 -> "corresponde al primer cuatrimestre"
        5, 6, 7, 8 -> "corresponde al segundo cuatrimestre"
        9, 10, 11, 12 -> "corresponde al tercer cuatrimestre"
        else -> "No esta dentro de los meses del año"
    }
)

fun mesesRango(mes: Int) = println(
    when (mes) {
        in 1..6 -> "Primer semestres del año"
        in 7..12 -> "Segundo  semestres del año"
        else -> "No corresponde a los meses que necesita"
    }
)


text:
Q: iOS 5 Google JSON - How to parse nested object? I Am trying to parse a Youtube playlist:
If my JSON is structured like:
{"apiVersion" ....
"items":[{"id2":"some-id","title":"songtitle",

I am perfectly able to parse the title via:
// Fill array
NSArray *items = [json objectForKey:@"items"];

// Get item from tableData
NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
// Set text on textLabel
[[cell textLabel] setText:[item objectForKey:@"title"]];

But if the JSON is like:
{"apiVersion" ....
"items":[{"id1": .... "video":{"id2":"some-id","title":"songtitle",

How can i reach the nested object title?
Just a simple thing, but i am banging my head on this for hours now. Gets frustrating, thanks for your suggestions!
[EDIT]
This is the full structure:
{
    "items":
    [
    {
    "video":
            {
                "title": "Number One",
                "description": "Description one"
            },
            {
             "title": "Number two",
                "description": "Description two"
            },
            {
                "title": "Number three",
                "description": "Description three"
            }
    },
    {
    "video":
            {
         "title": "Number One",
             "description": "Description one"
            },
            {
                "title": "Number two",
              "description": "Description two"
            },
            {
               "title": "Number three",
              "description": "Description three"
            }
    }

    ]
}

A: Try This:
NSArray *items = [[json valueForkey:@"items"]valueForkey:"video"];

A: NSMutableArray *items = [json valueForkey:@"items"];
for(int i =0;i<[items count]; i++)
{
  NSMutableArray *arrtitle = [[[items objectAtIndex:i]valueForkey:@"Video"]copy];
  for(int j =0;j<[arrtitle count]; j++)
  {
    NSString *title = [[arrtitle objectAtIndex:j]valueForkey:@"title"];
  }
}

maybe it will help you.

A: The problem is that your json is not valid. All the titles should be in array right? So they have to  be  in [ ]. You can use for example the following site to "debug" your json:
http://jsonformatter.curiousconcept.com/
Also, in iOS 5 you can use the new built-in JSON api. Here is a nice tutorial for that:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Nevertheless, here is how your json should look like I guess:
{
   "items":[
      {
         "video":[
            {
               "title":"Number One",
               "description":"Description one"
            },
            {
               "title":"Number two",
               "description":"Description two"
            },
            {
               "title":"Number three",
               "description":"Description three"
            }
         ]
      },
      {
         "video":[
            {
               "title":"Number One",
               "description":"Description one"
            },
            {
               "title":"Number two",
               "description":"Description two"
            },
            {
               "title":"Number three",
               "description":"Description three"
            }
         ]
      }
   ]
}

Good luck with your project ;)


text:
Q: Asp.Net Core Api Authorization I have an Asp.Net Core / ReactJs aopplication.  I'm using Microsoft.AspNetCore.ApiAuthorization.IdentityServer to authenticate the API.  However, I'm getting an error, which I believe is down to bad configuration.
If I run this locally, with the following config, everything works, and the app redirects to the log-in screen as expected:
  "IdentityServer": {
    "Clients": {
      "MyApp": {
        "Profile": "IdentityServerSPA",
      }
    },
    "Key": {
      "Type": "File",
      "FilePath": "Assets/selfsignedcert.pfx",
      "Password": "password"
    }
  },

However, if I change the config to the following:
  "IdentityServer": {
    "Clients": {
      "MyApp": {
        "Profile": "IdentityServerSPA",
        "RedirectUri": "https://localhost:5211/authentication/login-callback"
        "LogoutUri": "https://localhost:5211/authentication/logout-callback"
      }
    },
    "Key": {
      "Type": "File",
      "FilePath": "Assets/selfsignedcert.pfx",
      "Password": "password"
    }
  },

It errors (redirecting to the following):
https://localhost:5211/home/error?errorId=1234...

Looking at the auth request, from the client, they are exactly the same; however the second returns an error, while the first successfully redirects.
Is there something wrong with my config?  Alternatively, how can I debug this issue?

A: Both of your Uris in the non-working configuration point to logout. Is this really what you're trying to do?
In the first configuration, you're not defining any Uris, so they will have the following default values:
The redirect_uri defaults to /authentication/login-callback.
The post_logout_redirect_uri defaults to /authentication/logout-callback.
As documented here
Try changing the second configuration to match the default values to see if that helps.

A: The client configuration of redirect_uri and post_logout_redirect_uri must be identical to the IDP:
redirect_uri: 'https://localhost:5211/authentication/login-callback',
post_logout_redirect_uri: 'https://localhost:5211/authentication/logout-callback',

Or
redirect_uri: $'{IDPhost_config}/authentication/login-callback',
post_logout_redirect_uri: $'{IDPhost_config}/authentication/logout-callback',


text:
Q: AVPlayer video doesn't resize after device rotation I'm trying to make a AVPlayer video always full screen after device rotation. Here is my complete code. I do not understand why the video is not resized. Even if I use subclass like layerClass. After device rotation the videoView is cut, I do not see the video in full with. If someone has an idea. Thanks in advance.
import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVPlayer?
    var videoView: VideoContainerView!
    var playerLayer: AVPlayerLayer!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.videoView = VideoContainerView()
        self.videoView.frame = self.view.bounds
        self.videoView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        let path = Bundle.main.path(forResource: "GAVIDEO", ofType: "mp4")
        self.player = AVPlayer(url: NSURL(fileURLWithPath: path!) as URL)
        self.player?.isMuted = true

        self.playerLayer = AVPlayerLayer(player: self.player)
        self.playerLayer.frame = self.videoView.bounds
        self.playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill

        self.videoView.layer.addSublayer(playerLayer)

        self.videoView.layer.masksToBounds = true

        self.view.addSubview(self.videoView)

        self.player?.play()
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        self.videoView.frame = self.view.bounds
        self.playerLayer.frame = self.videoView.bounds

    }

}

class VideoContainerView: UIView {

    override class var layerClass: AnyClass {
        get {
            return AVPlayerLayer.self
        }
    }

    override func layoutSublayers(of layer: CALayer) {
        super.layoutSublayers(of: layer)
        guard layer == self.layer else {
            return
        }
        layer.frame = self.bounds
    }

}

A: try to use the size from the viewWillTransition, doing so:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
   super.viewWillTransition(to: size, with: coordinator)
    coordinator.animate(alongsideTransition: { (context) in
    }) { (context) in
        self.videoView.frame.size = size
        self.playerLayer.frame.size = size
    }
}

A: The following worked for me, where vc is a reference to the AVPlayerViewController that contains the AVPlayer view you would like to resize.
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
   super.viewWillTransition(to: size, with: coordinator)
   coordinator.animate(alongsideTransition: nil) { (context) in
      if size.height <= vc.view.bounds.height || size.width <= vc.view.bounds.width {
         vc.videoGravity = .resizeAspect
      }
      else {
         vc.videoGravity = .resizeAspectFill
      }
   }
}


text:
Q: Error: "Unable to Open Database" using sqite3 and Windows I'm a newbie to this, and can't figure out how to solve this error that I get when attempting to query from the database. The error reads:
rm: cannot unlink 'C:/Users/myName/Documents/GitHub/active_record_lite/lib../cats.db': Permission denied
Error: unable to open database "'C:\Users\myName\Documents\GitHub\active_record_lite'": unable to open database file

By going to "Properties" and viewing the "Security" tab, everything is checked under "Allow" for security, so I assume that the project and all subfiles have full permission (is this correct?).
I have a "cats.db" and "cats.sql" file in the project folder.
This is where I attempt to query from the database:
require_relative 'db_connection'
require 'active_support/inflector'

class SQLObject
  def self.columns
    cols = DBConnection.execute2(<<-SQL, @table_name)
      SELECT
        *
      FROM
        ?
    SQL

And here is a db_connection.rb file:
require 'sqlite3'

# https://tomafro.net/2010/01/tip-relative-paths-with-file-expand-path
ROOT_FOLDER = File.join(File.dirname(__FILE__), '..')
CATS_SQL_FILE = File.join(ROOT_FOLDER, 'cats.sql')
CATS_DB_FILE = File.join(ROOT_FOLDER, 'cats.db')

class DBConnection
  def self.open(db_file_name)
    @db = SQLite3::Database.new(db_file_name)
    @db.results_as_hash = true
    @db.type_translation = true

    @db
  end

  def self.reset
    commands = [
      "rm '#{CATS_DB_FILE}'",
      "cat '#{CATS_SQL_FILE}' | sqlite3 '#{CATS_DB_FILE}'"
    ]

    commands.each { |command| `#{command}` }
    DBConnection.open(CATS_DB_FILE)
  end

  def self.instance
    reset if @db.nil?

    @db
  end

  def self.execute(*args)
    puts args[0]

    instance.execute(*args)
  end

  def self.execute2(*args)
    puts args[0]

    instance.execute2(*args)
  end

  def self.last_insert_row_id
    instance.last_insert_row_id
  end

  private

  def initialize(db_file_name)
  end
end

Any advice/suggestions welcomed! Thanks!


text:
Q: Download file from Google Drive with its URI, without Google Drive API in Android I don't want the client to do any authentication at all, like signing in his email or anything. The client must just get all the shared files on click.
It has been given at many places, that it can be done by HTTP GET. I have tried it with different type files and sizes in Google Drive, but my code is giving me around 50 kb file, which of course is unreadable.
As an example here:

*

*The source file is a "Poocha.mp3".

*I have shareable ID returned by Google for this file.

*I have verified that this ID i.e. shareable string is shareable.

*I have taken all permissions in the Android manifest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

*I am testing this on a live device not on emulator.

*When I copy paste this link "https://drive.google.com/uc?export=download&id=0B5Isk4aTJApuZE9sVzg2MUxvc0U",
the file is downloaded in browser properly.

*But my code below is not working for any of the drive link. but but but

*When I upload the same file on my server and change the URL, the file gets downloaded correctly with the same code below. I have tried the same with "pictures.jpg" files, but every file on Google Drive gives incomplete 50 to 54 kb file and the same code works for the same file on my server.
My code:
protected String doInBackground(String... f_url) {
    int count;
    String id = "0B5Isk4aTJApuZE9sVzg2MUxvc0U";

    try {

        URL url = new URL("https://drive.google.com/uc?export=download&id=" + id);

        HttpURLConnection c = (HttpURLConnection) url.openConnection();

        c.setRequestMethod("GET");

        c.connect();

        int lenghtOfFile = c.getContentLength();

        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        String out = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sifr/album";

        File filedir = new File(out);
        if (!filedir.exists()) {
            filedir.mkdirs();
        }
        OutputStream output = new FileOutputStream(out + "/Poocha.mp3");

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress("" + (int) ((total * 100) / lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();

        output.close();
        input.close();

    } catch (Exception e) {
        Log.i("GetPathLst errr", e + "");
    }
    return null;
}

Could somebody point out the problem?

A: I have tried your code with a shared file on my Drive account and it download the file OK. The shared URL I get from Google Drive is of the format:
https://drive.google.com/open?id=UUjBUTaQyakU0B0HGOaFKlT5geXN

Other than that, you code worked without modification. (btw, that's not the real id).
I hope this helps.

Update
The above answer, while true, is not your problem. I just tried your URL on my Android device with Google Drive installed and Drive told me that the owner has "trashed" the file. When I tried the same url in my browser, it downloaded OK.
Evidently, the file is available for download but the Drive app seems to make the additional check to make sure the file is not trashed. Browsers don't and can't make this same check.
Move your file from the trash bin or try a different file. It should work.


text:
Q: SQL Find All Tables and Fields Where a Specific Value is Present I'm not an expert on SQL so I'm having a little bit of a hard time trying to implement or modify what I've seen online for my case.
Trying to build a query from a Schema I'm not familiar with. The Schema has 50+ tables each with varying amounts of columns.
I have a couple of values but can't find the field or table those values are in.
Was trying to find these values with something like this (see code below) which would help but I can't figure out a way to:

*

*Include all columns without having to type them all out inside the IN operator.

*Not sure if there is a way to modify the code so I wouldn't have to run it for each table in the Schema.

SELECT
*
FROM
    XX_PROD.XXX_MART.FACT_SALES_ORDER AS FSO

WHERE 'AVP' IN (FSO.COLUMNS)

LIMIT
10000

A: I tried running a sub-query for the columns to at least be able to run all columns per table but surprisingly that didn't work.
Used this code to at least be able to get a list of the columns in a specific Schema that might contain the values I'm looking for. It did save me a decent amount of time:
SELECT TABLE_NAME,COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE
   TABLE_SCHEMA like 'XXXX_MART'
   AND COLUMN_NAME like '%START_DATE%'

ORDER BY
TABLE_NAME ASC

A: This SQL script is not going to be fast, but it works:

*

*Find all string columns in tables in this database.

*For each string column found above, we are going to insert the # of rows that match the condition.

declare
    table_name string;
    column_name string;
    all_columns cursor for (
        -- find all string columns in tables in this database
        -- add restrictions here for less scans later
        select table_schema, table_name, column_name
        from information_schema.columns
        where table_schema != 'INFORMATION_SCHEMA'
        and data_type = 'TEXT'
    );
begin
    -- create a table to store results
    create or replace temp table discovery_results(table_name string, column_name string, matches int);
    for record in all_columns do
        table_name := record.table_schema || '.' || record.table_name;
        column_name := record.column_name;

        -- for each string column found above, we are going to insert the # of rows that match the condition
        insert into discovery_results
            select :table_name, :column_name, count(*)
            from identifier(:table_name)
            -- change the condition you are looking for here
            where identifier(:column_name) like '%string%'
        ;
    end for;
    return 'run [select * from discovery_results] to find the results';
end;

select *
from discovery_results

This would work faster if we would parallelize each column scan.