text:
Q: Why does the connection to ASE fail when password encryption is required? How can I password encrypt the database server connections from PHP to Sybase ASE?
The PHP connection to ASE fails when net password encryption reqd = 1.
How can we make a PHP DB connection to ASE with password encryption? Is there a PHP keyword or parameter that we need to set on the client side connection?

A: Below is a solution to this problem in term of able to connect from a Linux 64 bit base machine with PHP version 5.3.6 and Sybase driver from Sybase CTISQL Utility/15.7/P-EBF19975 ESD #3/DRV.15.7.0.3. While we got this to work, we need to have Apache to work in addition to this, I am hoping Sybase support is able to help us with that as well as they have with solution below to our question. I am posting this here for everyone benefit.  Note: AFAICT, this is not a supported solution by Sybase.  Please use it as your own risk.
Few things need to happen for this to work:

*

*I've use the latest Debian Stable 6.05 squeeze 64 bit

*I've install ebf19977(developer kit with open client, yes the number is off, that's not a mistake, you will see when you install it) downloaded from Sybase

*Download PHP 5.3.6 from php.net website to be compile from source.

Step 1)  I am assume one should easily set this up.  Make sure you have sudo access
Step 2)  To install the developer kit you need to type the whole path to where the setup.bin file is locate like so type in sudo /home/btran/ebf19977/setup.bin , this will start the setup, pretty much follow instructions there to to install OpenClient and its associate tools.  Make sure that Open Client, and PHP library are install.
Once you done the install there are a few other steps to do:
Set all Sybase environments variables by executing the SYBASE.sh in the root directory at /opt/sybase
sudo cat /opt/sybase/SYBASE.sh >> /etc/profile , if necessary source /etc/profile

This will set most of the variables, but you need to add a couple variable that is not there:
    PHPRC=/opt/sybase/OCS-15_0/config
    LD_LIBRARY_PATH=/opt/sybase/OCS-15_0/php/php536_64/lib:/opt/sybase/OCS-15_0/lib

Your /ect/profile should look something like this:
    # ------------------------------------
    #    Sybase Product Environment variables
    # ------------------------------------
    SYBASE="/opt/sybase"
    export SYBASE
    SYBASE_OCS="OCS-15_0"
    export SYBASE_OCS
    INCLUDE="/opt/sybase/OCS-15_0/include":$INCLUDE
    export INCLUDE
    LIB="/opt/sybase/OCS-15_0/lib":$LIB
    export LIB
    PATH="/opt/sybase/OCS-15_0/bin":$PATH
    export PATH
    LD_LIBRARY_PATH="/opt/sybase/OCS-15_0/php/php536_64/lib:/opt/sybase/OCS-15_0/lib:/opt/sybase/OCS-15_0/lib3p64:/opt/sybase/OCS-15_0/lib3p":$LD_LIBRARY_PATH
    export LD_LIBRARY_PATH

    PHPRC="/opt/sybase/OCS-15_0/config"
    export PHPRC

    JAVA_HOME="/opt/sybase/jre32"
    export JAVA_HOME

    RIBO_HOME="/opt/sybase/jutils-3_0/ribo"
    export RIBO_HOME
    # ------------------------------------

Then, you will also need to made modification to the interfaces file located at root directory /opt/sybase to look something like this, please do not use this, use your info:
    dev
        master tcp ether dev.company.com 4425
        query tcp ether dev.company.com 4425

    prod
        master tcp ether prod.company.com 4425
        query tcp ether prod.company.com 4425

    ribo
        master tcp ether testhost.company.com 5005
        query tcp ether testhost.company.com 5005

You will also need to made modification to the ocs.cfg to get PHP to initiated correctly, this located in the folder /opt/sybase/OCS-15_0/config to look like this:
    ;;;;;;;;;;;
    ; This is the default external configuration definition file. Feel free
    ; to add your own customizations.
    ;
    [DEFAULT]
    ; This is the default section loaded by applications that use
    CS_SEC_ENCRYPTION = CS_TRUE
    [ANSI_ESQL]
    ; This section defines configuration which an ANSI conforming
    CS_CAP_RESPONSE = CS_RES_NOSTRIPBLANKS
    CS_EXTRA_INF = CS_TRUE
    CS_ANSI_BINDS = CS_TRUE
    CS_OPT_ANSINULL = CS_TRUE
    CS_OPT_ANSIPERM = CS_TRUE
    CS_OPT_STR_RTRUNC = CS_TRUE
    CS_OPT_ARITHABORT = CS_FALSE
    CS_OPT_TRUNCIGNORE = CS_TRUE
    CS_OPT_ARITHIGNORE = CS_FALSE
    CS_OPT_ISOLATION = CS_OPT_LEVEL3
    CS_OPT_CHAINXACTS = CS_TRUE
    CS_OPT_CURCLOSEONXACT = CS_TRUE
    CS_OPT_QUOTED_IDENT = CS_TRUE
    ; End of default sections

    [isql]
    CS_SEC_ENCRYPTION = CS_TRUE

    [PHP]
    CS_SEC_ENCRYPTION = CS_TRUE

    ; This is a sample section showing how you might alter configuration
    ; properties for you Embedded SQL application.
    [SAMPLE_ESQL]
    ; use most of the ANSI properties defined above
    include = ANSI_ESQL
    ; but override some default properties
    CS_OPT_CHAINXACTS = CS_FALSE ; run in autocommit mode
    ;;;;;;;;;

Note: Very Critical to check for the existence of the php.ini file in the same directory as well /opt/sybase/OCS-15_0/config (this pointing the exention file, look at the environment variable LD_LIBRARY_PATH="/opt/sybase/OCS-15_0/php/php536_64/lib)
you php.ini should read like this:
    extension=/opt/sybase/OCS-15_0/php/php536_64/lib/sybaseasephp.so

Step 3) compile PHP from source, again Sybase call for 64 bit.
I down load the source to /opt/php-5.3.6 for persistent with where most app install for Linux.
    cd to /opt/php-5.3.6

    ./configure

VERY IMPORTANT to note, this is where we ran into a snag, if I choose any other configure option and not default ./configure, PHP will fail to load with error below:
btran@sls-baonix:/opt/php-5.3.6$ php ~/test-dev.php
PHP Warning:  PHP Startup: Unable to load dynamic library
'/opt/sybase/OCS-15_0/php/php536_64/lib/sybaseasephp.so' -
/opt/sybase/OCS-15_0/php/php536_64/lib/sybaseasephp.so: undefined
symbol: executor_globals in Unknown on line 0

Fatal error: Call to undefined function sybase_connect() in
/home/btran/test-dev.php on line 10
]

Reason we need other options is we need it also to work with Apache.  We got it now to work with PHP, but we need to be able to initiate PHP from website so the dependencies is that PHP beside support Sybase, it also need to support Apache.  If any PHP expert out there has solution to this please jump in and help us out.


text:
Q: For Loop to rename objects in a data frame (+ ignore NA) in R I have a data frame that contains a column with binary variables (pointed or broad). To do my calculations I need to replace them with 0 or 1. I want to write a for loop which is doing this for me.
My code:
binary_To_Number<-function(df)
{
 for(i in df)
   {
      if(i=="pointed")
        {
          i<-1
        }
      else if(i=="broad")
        {
          i<-0
        }
      else if(is.na(i))
        {
          print("NA")
        }
      else
        {

        }
    }
}

binary_To_Number(town$shape)

I tried to use this piece of code. My first problem with it is that I don't know how to save the results. So my code is changing the i temporarily but won't save it in the df. I know that you can create an empty storage vector to store results in it, but can I replace the variable in my df immediately?
The second problem is that my code stops and gives me an error message if it comes to an i which contains NA.
Error in if (i == "pointed") { : missing value where TRUE/FALSE needed

Is there something I can do about it or do I need to replace the NA with a placeholder first?

A: You can also use dplyr (ensures 0 for not pointed):
library(dplyr)
df <- df %>%
  mutate(
    isPointed = as.integer(tolower(shape) == 'pointed')
  )

Output:
    shape isPointed
1 Pointed         1
2   broad         0
3 pointed         1

The dataframe I used:
df <- data.frame(
  shape = c('Pointed', 'broad', 'pointed'),
  stringsAsFactors = FALSE
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change "reply with message" text I know how to change text for RELY WITH MESSAGE option, however
"Can't talk right now" part can't be changed in setting.
Is there an app or a modification that can change "Can't talk right now" part?
To change text for RELY WITH MESSAGE OPTION go to

*

*Settings->Phone->Reply with Message

A: If your device is jailbroken, you can use this solution to change the default reply message prefix:

iFile will let you edit the .plist strings. How ever you do it, the .plist file is in /System/Library/PrivateFrameworks/TelephonyUtilities/English.Iproj folder (if you use English. What I don't know is if this changes anything in the sent text


text:
Q: How to successfully return the metadata off of an mp3 file while avoiding a null pointer exception When I attempt to run the program that takes the metadata and prints it from an mp3 file, I am returned with an "Exception in thread "main" java.lang.NullPointerException at project.mp3MetaData.main(musicdj.java:18)". For this class you need the jid3lib jar. How do I avoid this exception and do I need to pass any variables through the tags at the bottom?
package 1234;

import java.io.File;
import java.io.IOException;

import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.ID3v1;

public class mp3MetaData {

public static void main(String[] args) throws IOException, TagException {

    // TODO Auto-generated method stub
    File sourceFile = new     File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
    MP3File mp3file = new MP3File(sourceFile);
    ID3v1 tag = mp3file.getID3v1Tag();
    System.out.println(tag.getAlbum());
    System.out.println(tag.getAlbumTitle());
    System.out.println(tag.getTitle());
    System.out.println(tag.getComment());

}

}

Any help will be greatly appreciated.

A: Your MP3 file might not contain an ID3 tag. So check whether tag is null or not, before using it. Something like this:
public static void main(String[] args) throws IOException, TagException
{
    File sourceFile = new File("/Users/JohnSmith/Desktop/MusicTester/1234.mp3");
    final MP3File mp3file = new MP3File(sourceFile);
    final ID3v1 tag = mp3file.getID3v1Tag();
    if (null == tag)
    {
        System.out.println("No ID3 tag found!");
    }
    else
    {
        System.out.println(tag.getAlbum());
        System.out.println(tag.getAlbumTitle());
        System.out.println(tag.getTitle());
        System.out.println(tag.getComment());
    }
}


text:
Q: Simple string concatenation fails I have the following code:
from yahoo_finance import Currency

symbolslist  = ["EURUSD","EURGBP","EURJPY","EURRUB","USDCAD","USDCHF","AUSUSD"]

for i in range(len(symbolslist)):
        symbol = symbolslist[i]
        nomisma = Currency(symbol).get_rate()

        quota = symbol + " = " + nomisma
        print quota

And I get the result:
EURUSD = 1.0891
EURGBP = 0.7322
EURJPY = 129.7440
EURRUB = 63.0560
USDCAD = 1.2614
USDCHF = 0.9622
Traceback (most recent call last):
  File "yahoopy.py", line 13, in <module>
    quota = symbol + " = " + nomisma
TypeError: cannot concatenate 'str' and 'NoneType' objects

I'm aware that this error has been talked about in this link.
But I was hoping that I could overcome this bug without resorting to mysql.

A: The problem is a typo. Instead of AUDUSD you wrote AUSUSD. Fix it and the error will be gone:
symbolslist  = ["EURUSD","EURGBP","EURJPY","EURRUB","USDCAD","USDCHF","AUDUSD"]

Still it is a good idea to use format as @BhargavRao suggested to catch such bugs.

A: Add an if clause above your concat statement
if nomisma:
    quota = symbol + " = " + nomisma

Assumption - It means that AUSUSD is not present in your database, that is why Currency(symbol).get_rate() is returning None. Also as mentioned here it is AUDUSD and not AUSUSD
Note : It is better to use format to concat as in
quota = "{} = {}".format(symbol,nomisma)


text:
Q: What is another alternative to `TextChanged` event I am working in windows form and have a few textboxes on a form.
These textboxes from top to bottom are connected, so if the text changes in textbox1, then txtbox2 and txtbox3 have to comply, if something changes in textbox2 then 3 has to comply;... and so on ... not going to bore you.
Now I was looking for an alternative, more efficient way of calling the textchanged event on the textboxes so it doesn't do everything everytime, even if one charater has changed....
Something like focus off textbox event ... or some other alternative .
This would be in vb.net and windows form.

A: You can use the TextBox.LostFocus event inherited from Control.LostFocus.
This event is fired when the control looses focus, like Tab or clicked on another control.

A: TextBox1.LostFocus perhaps? Or enable validation on the controls.
Control focus event order:
http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.lostfocus.aspx
CausesValidation:
http://msdn.microsoft.com/en-gb/library/system.windows.forms.control.causesvalidation.aspx


text:
Q: ip адрес. база моб.операторов Добрый день уважаемые участники. Помогите разобраться со следующим вопросом.
В общем потребовалась мне как-то база мобильных операторов. Сам я в этом новичек, и в ip ниче не понимаю=( к сожалению это так. Но, учусь быстро и рассчитываю на вашу помошь.
Скачал я одну базу, где все значения представлены в xml файле вида:
<operator id="11" name="TELE2" label="tele2" tld="RU" country="Россия" publish="1" mnc="250-20">
  <range ip1="1306001408" ip2="1306132479" mode="0" global="0" />
  <range ip1="1404225536" ip2="1404227071" mode="0" global="0" />
  <range ip1="1404256256" ip2="1404272639" mode="0" global="0" />
  <range ip1="1404272640" ip2="1404305407" mode="0" global="0" />
  </operator>

Как я понял, ip1 и ip2 это диапазон ip адресов... Как видите адреса представлены в числовом виде (если это так).
Так вот у меня возник вопрос.

*

*Как преобразовать адрес из базы в привычный вид (192.168.0.1 - пример),или наоборот, адрес преобразовать к виду из базы. читал что сравнивать целочисленные адреса проще, и меньше времени это занимает.

*Например определил я ip адрес через $_SERVER['REMOTE_ADDR'], выполнил пункт 1. Но не понимаю как сравнить его с базой? Меня ставит в тупик этот диапазон. Вот вообще не соображу что с чем сравнивать что-бы не пролететь и все учесть....

Пока вроде все... Сильно не ругайтесь, это для меня ново и я только учусь. Буду признателен за подробную помощь нубу=)
UP.
Да, действительно ip закодирован в ip2long. Попробовал некоторые пробить, получилось, оператор совпал. Большое спасибо!
Понял, буду сравнивать так...
mysql_query("SELECT COUNT(*) FROM `operator` WHERE `min` <= '$iplong' AND `max` >= '$iplong'"

A: какой нафиг explode()? Зачем велосипед делать, уже давно все написано!
ip2long('127.0.0.1'); // получим числовое значение

long2ip(2130706433); // получим IP из числа


text:
Q: Remove dependency of Territory object from already released managed package Salesforce has announced retiring the support for original territory management https://help.salesforce.com/articleView?id=000273181&type=1 and we have our managed package using the standard salesforce Territory object which is available after enabling original Territory management. So as of today the package is dependent on Territory management and can't be installed without enabling territory management.
We are in the process of migrating from original territory management to Enterprise Territory Management.
We have customers using this package so need to make the package compatible with both old territory management and Enterprise Territory Management 2.0 till everyone is migrated to TM2.0.
As a first step want to remove the package dependency on Territory object. I am aware of using dynamic SOQL but issue is the territory object is part of released package and it has some custom fields which are being referenced throughout the code.
My question is we can't delete the Territory object from the package as it has these custom fields and need to keep it still compatible with original Territory Management for sometime till we completely migrate everyone to TM2.0
Any idea how to achieve keeping package compatible with both TM without having any hard references?
Note: This standard salesforce Territory object has custom fields as well which are being used across application.


text:
Q: Retrieve Blackberry OS in Blackberrywebworks using javascript How to retrieve Blackberry OS version in Blackberrywebworks using javascript?

A: Just use blackberry.system.softwareVersion and don't forget to add <feature id="blackberry.system" /> to your config.xml
You can find full docs here
https://developer.blackberry.com/html5/apis/blackberry.system.html#.softwareVersion


text:
Q: Recode continues variable based on predefined range in r I would like to recode a continuous variable based on predefined intervals and categorize the variables. I know an ifelse would work but it seems to me very tedious.  Here how my sample dataset looks like:
library(ggplot2)

df <- data.frame(
  id = c(1,2,3,4,5),
  score = c(1.5, 2, 2.5, 3.2, 4.5))

> df
  id score
1  1   1.5
2  2   2.0
3  3   2.5
4  4   3.2
5  5   4.5

here my predefined intervals:
intervals <- cut_interval(seq(1, 7), n=5)
> intervals
[1] [1,2.2]   [1,2.2]   (2.2,3.4] (3.4,4.6] (4.6,5.8] (5.8,7]   (5.8,7]
Levels: [1,2.2] (2.2,3.4] (3.4,4.6] (4.6,5.8] (5.8,7]

With these intervals My desired/recoded dataset should look like this:
df <- data.frame(
  id = c(1,2,3,4,5),
  score = c(1.5, 2, 2.5, 3.2, 4.5),
  intervals = c("[1,2.2]", "[1,2.2]", "(2.2,3.4]", "(2.2,3.4]", "(3.4,4.6]"),
  cat = c(1,1,2,2,3))

> df
  id score intervals cat
1  1   1.5   [1,2.2]   1
2  2   2.0   [1,2.2]   1
3  3   2.5 (2.2,3.4]   2
4  4   3.2 (2.2,3.4]   2
5  5   4.5 (3.4,4.6]   3

Any thoughts?
Thanks!

A: It sounds like you would just need to retrieve the cut points from intervals and apply them to df$score. In base R you could do
df$intervals <-
  cut(df$score, breaks = unique(as.numeric(
    gsub("[\\(|\\]|\\[|\\]|\\)]", "", unlist(strsplit(levels(
      cut(seq(1, 7), breaks = 5)
    ), ",")))
  )))
df$cat <- as.numeric(df$intervals)

A: Here's some possibly relevant oneliners with (my) santoku package:
library(santoku)

# cut into equal-sized intervals of size 1.2
df$cat <- chop_width(df$score, 1.2)

# cut into exactly 5 intervals of equal width
df$cat <- chop_evenly(df$score, 5)


text:
Q: How to restrict access to web pages for different types of users? I have a web application where there is one admin and many users. When a user logs in he is taken to a certain page from which he can perform other operations which lead him to other pages restricted to him .The same goes for the admin too. But if i change the url to the restricted page during runtime a user can access an admin's page and vice versa. I have heard about using membership access. But i dont know how its done. I am  using an sql database where the login details are stored in a table.
So how do i restrict access? I have heard it has to do something with the web.config? Is it possible to achieve the same result by using just code behind?

A: You should use the ASP.NET Membership provider. It will give you a lot of stuff out of the box. There's a good tutorial by Scott Mitchell that will guide you through this process.

*

*Part 1

*Part 2

*Part 3

*Part 4

*Part 5

A: When loading your pages, you might have to check if the user have the right permission and allow access or redirect him to another page.
If ! user can access page {
   redirect
}
Your page content.


text:
Q: Need a common way to write an array for Windows 8 Store, Iphone, and Android I am currently writing an app that takes data and presents it to the user in a type of Q and A study program. First app that I am writing so outside of my normal basic C++ shell on this. Currently developing the windows 8 version in C# but I don't want to have to answer 4000 entries with multiple data points for each question later on. Any suggestions on how I could do this?
tl;dr A way to use a common data set that is transferable between android, Iphone, and Windows 8 store apps.

A: If these are constant data you can present them as an XML file
<questions>
<question id="1" text="Your favorite artist">
<answer id="1" text="Picasso"/>
<answer id="2" text="Rafael"/>
<answer id="3" text="Don't know any"/>
</question>
</questions>

All those platforms have XML parsers.
Answers can be stored as an SQL database with 1 table: fields: Question id and Answer id.

A: Do you plan to store the data on the device or have it available in the cloud?  The latter approach provides much more flexibility for you, you can modify the data at any time - adding information, making corrections, etc. - and that same data set would be available through services to all of your disparate clients.
You might take a look at Window Azure Mobile Services (or other Background-as-a-Service offering) to provide that storage and service endpoint.  WAMS fronts a SQL database, but provides SDKs for all the mobile platforms to easily access the data.  There's also a free tier and you can try anything on Azure out for 90-days with no charge or commitment.
For offline capabilities, you could still leverage Mobile Services via background tasks to make sure some subset of your question bank is available on device and then sync later when you are on-line.  It's a bit more work to provide that type of implementation, but it makes for a much richer experience for the user.


text:
Q: V8, run-tests.py fails When I compile v8, following https://github.com/v8/v8/wiki/Building-from-Source run-tests.py fails with the error message:
Error: Failure: expected <11/11/1500>, found <12/10/1500>.
    at fail (/.../v8/v8/test/intl/assert.js:105:9)
    at assertEquals (/.../v8/v8/test/intl/assert.js:114:5)
    at /Users/holmeshe/.../v8/v8/test/intl/date-format/format-test.js:50:1

A: there are 2 bugs in the date-format/format-test.js:
1. in javascript, month starts from 0,
2. UTC time should be used to create the date object.
So the assertation should be modified to:
assertEquals('12/11/1500', dtf.format(new Date(Date.UTC(1500,11,11,12,0,0))));

A: This doesn't really belong on StackOverflow, I think...
You can file a bug at https://bugs.chromium.org/p/v8/issues/list. Note that all tests are passing fine on V8's buildbots (and, I just checked, on my machine too), so please include all information that might be helpful for determining what's different on your machine (which revision did you check out? On which OS? What timezone is your machine in? Anything else you can think of?).
If you have a suggested fix, please follow the Contribution Guidelines.


text:
Q: Pagedown Markdown editor : issue with images When using PageDown, there is some problem when inserting an image which is too big.
It is not redimensioned to a size that would fit in the editor's width (that would be possible with )
Example : try to insert this image URL http://upload.wikimedia.org/wikipedia/commons/4/4b/Apple_pie.jpg in this editor :
http://www.markitdown.net/markdown.
How to make image fit in the container with Markdown ?
(this is done on StackOverflow's editor)

A: You can append =WIDTHxHEIGHT after the URL to resize the image. Do not forget the space before the =
![](./applePie.png =100x200)

Height is also optional so you can do...
![](./applePie.png =100x)

If you're referring to StackOverflow images, there's a good description here off what's possible: https://stackoverflow.com/editing-help#images

A: When working with the Pagedown editor
http://pagedown.googlecode.com/hg/demo/browser/demo.html
it finally works by adding
#wmd-preview img { max-width: 500px; }

All images (even big ones) will have a max width of 500px.

A: The only way which works with the editor you provide is this:

Which render:

instead of:

But it's not in the markdown spirit...


text:
Q: Pyspark replace NA by searching another column for the same value Values from Column_1 can't have multiple values on column_2. So, for the same Id we have the same value.
column_1 column_2
    52     A
    78     B
    52

Expected
column_1 column_2
    52     A
    78     B
    52     A

Which means searching column_1 for the first column_1 value that matchs the same missing column_2 id.
I've a working solution using R, but using pyspark I couldn't find a similar approach.

A: Since the same ID will always have the same value, as you have stated
One way to achieve this is to use the inherent sequence order present within your data and use the lag value to populate the missing values
You can utilise Lag Function to generate the previous value associated to your col_1 and Coalesce to get the first non-null value from the two
Data Preparation
df = pd.DataFrame({
        'col_1': [52,78,52,52,78,78],
        'col_2': ['A','B',None,'A','B',None]
})

sparkDF = sql.createDataFrame(df)

sparkDF.show()

+-----+-----+
|col_1|col_2|
+-----+-----+
|   52|    A|
|   78|    B|
|   52| null|
|   52|    A|
|   78|    B|
|   78| null|
+-----+-----+

Lag
window = Window.partitionBy('col_1').orderBy(F.col('col_2').desc())

sparkDF = sparkDF.withColumn('col_2_lag',F.lag('col_2').over(window))

sparkDF.show()

+-----+-----+---------+
|col_1|col_2|col_2_lag|
+-----+-----+---------+
|   52|    A|     null|
|   52|    A|        A|
|   52| null|        A|
|   78|    B|     null|
|   78|    B|        B|
|   78| null|        B|
+-----+-----+---------+

Coalesce
sparkDF  = sparkDF.withColumn('col_2',F.coalesce(F.col('col_2'),F.col('col_2_lag'))).drop('col_2_lag')

sparkDF.show()

+-----+-----+
|col_1|col_2|
+-----+-----+
|   52|    A|
|   52|    A|
|   52|    A|
|   78|    B|
|   78|    B|
|   78|    B|
+-----+-----+

A: I would do something like this, using max :
from pyspark.sql import functions as F, Window

df.withColumn(
    "column_2",
    F.coalesce(
        F.col("column_2"), F.max("column_2").over(Window.partitionBy("column_1"))
    ),
).show()


text:
Q: Using Spring Java Config to register Apache Camel dataFormats I'm using Apache Camel version 2.10.0 and I currently have the following in my camelContext in XML format:
<dataFormats>
    <json id="jack" library="Jackson" unmarshalTypeName="package.name.PojoClassName"/>
</dataFormats>

I want to move it to Java Config, but I can't seem to do it without using a deprecated method. This is a trimmed down version of what I got:
public class MyCamelConfig extends CamelConfiguration {
    @Override
    protected void setupCamelContext(CamelContext context) {
        // "getDataFormats()" is deprecated
        context.getDataFormats().put("jack", getJack());
    }

    @Override
    public List<RouteBuilder> routes() {
        // bunch of route builders created and returned
    }

    @Bean
    public DataFormatDefinition getJack() {
        //create and return a DataFormatDefinition
    }
}

I have been unable to find a non-deprecated way to do this.

A: It looks like the following works:
@Override
protected void setupCamelContext(CamelContext context) {
    ModelCamelContext modelContext = (ModelCamelContext) context;
    modelContext.getDataFormats().put("jack", getJack());
}

I just cast the CamelContext to a ModelCamelContext.


text:
Q: ASP.Net dual OWIN authentication - how to prevent redirect to AzureAD-login for non-AD-users We have a .NET 4.7.2 MVC website in which we've implemented dual authentication - against AzureAD using OpenIdConnect and default application-cookie-authentication for non-AD-users.
AD-users are redirected to Microsoft login and we have a custom login page for the non-AD-users.
Our problem is that when we log in a user in our custom login page using AuthenticationManager.SignIn, the user is redirected to the Microsoft login anyway.
I've managed to fix this by adding the following to the RedirectToIdentityProvider-func in the OpenIdConnect-configuration in Startup.cs:
if (context.Request.Path.ToString().Contains("login"))
{
    context.HandleResponse();
}

But this seems like an ugly hack. What is the proper way of handling this problem?

A: I solved this problem adding the following line on OpenIdConnectAuthenticationOptions:
AuthenticationMode = AuthenticationMode.Passive

Reference:
https://github.com/aspnet/AspNetKatana/issues/300


text:
Q: Author name in bibliography contains special letters I have a reference for article where author name contains several specific characters. Do I need a specific package for this case:
Here is the reference:
@article{matouvsek1998thel2,
  title={On the {$L_2$}-discrepancy for anchored boxes},
  author={Matou{\v{s}}ek, Ji{\v{r}}{\i}́},
  journal={Journal of Complexity},
  volume={14},
  number={4},
  pages={527--556},
  year={1998},
  publisher={Elsevier}
}

A: Have you seen the posting How to write "ä" and other umlauts and accented letters in bibliography?
Let's assume that you use the Computer Modern font family and pdfLaTeX to compile your document. In that case, you do not need to load any packages to typeset the three accented characters in the author field of your bibliographic entry -- r-with v-check, s-with-v-check, and dotless-i. (Aside: did you mean to write {\'i}, i.e., i-with-sharp-accent, instead of dotless-i?) However, for some other accented characters, such as ogonek-a or ogonek-k, you will need to load the fontenc package with the option T1.
If you have the option to employ either XeLaTeX or LuaLaTeX, you won't have to load any special packages.


text:
Q: Firebase Real-time Database name and value I am an amateur app developer. I am now trying to build a messaging app for iOS. But I have some hard times understanding the realtime firebase database. I don't understand the value and the name section when you press the plus sign.

A: The value and name section you mention is a tool for designing the structure of your database. Firebase uses a very popular style of NoSQL database: Key-value stores. The concept is not so complicated once you know the basic JSON syntax.
Here's an example from an iOS app I built. The whole diagram is a JSON object. The keys have to be strings, just like the "orders" key below.  The value must be a valid JSON data type (string, number, object, array, boolean or null), which is an object in this case. And it goes on like that...

Try this tutorial.
Cheers, Tim!


text:
Q: np.where() with multiple outputs I am currently performing a row-wise calculation on a pd.DataFrame using df.apply(foo), where foo is effectively as follows:
def foo(row):
    n = row['A']
    d = row['B']

    if n <= 0:
        return 0
    if d <= 0:
        return 100
    return n / d * 100

This seems to be begging to be simplified into an np.where.
I have other cases with only one if statement (i.e. if n <= 0), which I have already simplified into
np.where(df['A'] <= 0, 0, df['A'] / df['B'])

However, I can't see how to do the same with the double-if case. At least not elegantly. I could do
np.where(df['A'] <= 0, 0, np.where(df['B'] <= 0, 100, n / d * 100))

But this would seem to run through the entire dataframe twice, once for each np.where call.
Is there a better way of doing things? Or, alternatively, is the use of np.where and the vectorization it brings so great that running through the table twice with np.where is still better than only once with pd.apply?


text:
Q: iOS 4.0 Twitter Integration I am developing an application that requires login with social media (Facebook, twitter). From these services I just need to obtain the session tokens. So, when the user presses the "Login with Twitter button", I want to have a sign in method similar to what the Facebook application does, where it signs in the user and then returns with a session token.
I would like some pointers on where to start. I searched the official API documentation, but is seems developing with Oath is way complicated and demands time that I can't afford to devote at this point. I stumbled upon MGTwitterEngine, But I failed to see a way of obtaining the OAuth's session's token, and also, it hasn't been updated in 3 years! https://github.com/mattgemmell/MGTwitterEngine
Can anyone point me into the right direction?

A: You should use the APIs and OAuth.  It would probably be more difficult and take longer to try to avoid OAuth.  Just put up the twitter or facebook login pages in a UIWebView and go from there.
Getting the oAuth token from Facebook is very straight forward, the iOS facebook API provides it.  Getting the Twitter API token is just a matter of parsing the URL that is returned to you.  Niether is very difficult.


text:
Q: Angular-cli + primeng require is not defined I'm using angular-cli@1.0.0-beta.14 (webpack) and primeng@1.0.0-beta.15.
After create a fresh angular-cli project i made a few changes to add primeng:
1 on package.json:
"primeng": "^1.0.0-beta.15"

2 on angular-cli.json:
"styles": [ "styles.css", "../node_modules/primeng/resources/themes/omega/theme.css", "../node_modules/font-awesome/css/font-awesome.min.css", "../node_modules/primeng/resources/primeng.min.css" ],
"scripts": [ "../node_modules/primeng/primeng.js" ]

3 on app.module.ts:
@NgModule({ declarations: [ AppComponent ],
imports: [ BrowserModule, FormsModule, HttpModule, PanelModule ],
providers: [], bootstrap: [AppComponent] }) export class AppModule { }

Problem:

Uncaught ReferenceError: require is not defined  Unexpected value
  'undefined' imported by the module 'AppModule'

Any help to add primeng to angular-cli... will we great! :)

A: So just about everything you have there looks good.
The issue lies in that you're attempting to include primeng as a script tag (which is for global libraries like jQuery). But since primeng deploys modules you can simply import it in your module and then supply that to your NgModule like this:
import { ButtonModule } from 'primeng/components/button/button';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    ButtonModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And then you'll also want to remove the reference to primeng.js from your angular-cli.json


text:
Q: How can I use Azure App Configuration service within Azure Function v1 (.NET Framework) TL;DR: How can I use Managed Service Identities in an Azure Function v1 for configuring via Azure App Configuration?
I'm trying to make use of Azure App Configuration from within an Azure Function v1 using .NET Framework. I would ideally like to make use of the ConfigurationBuilders.
This would mean using the SimpleJsonConfigBuilder class when running on a dev machine but using AzureAppConfigurationBuilder when hosted in Azure.
I've got it working with our Web API projects but I'm stuck when it comes to the Azure Functions.
The problem as I see it, is that the Azure Function host is using its own web.config and therefore cannot be modified with the config I would use in a web project.
<configuration>
  <configSections>
    <section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
  </configSections>
  <configBuilders>
    <builders>
      <add name="Environment" type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Environment, Version=1.0.0.0, Culture=neutral" />
      <add name="Json" optional="true" mode="Greedy" jsonFile="~/App_Data/settings.json" type="Microsoft.Configuration.ConfigurationBuilders.SimpleJsonConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Json, Version=1.0.0.0, Culture=neutral" />
      <add name="AzureViaConnectionString" optional="true" mode="Greedy" connectionString="${AppConfigConnectionString}" type="Microsoft.Configuration.ConfigurationBuilders.AzureAppConfigurationBuilder, Microsoft.Configuration.ConfigurationBuilders.AzureAppConfiguration" />
      <add name="AzureViaMsi" optional="true" mode="Greedy" endPoint="${AppConfigEndpoint}" type="Microsoft.Configuration.ConfigurationBuilders.AzureAppConfigurationBuilder, Microsoft.Configuration.ConfigurationBuilders.AzureAppConfiguration" />
    </builders>
  </configBuilders>
  <appSettings configBuilders="Environment,Json">
...

Even if I don't use the xml config, which is I'm assuming will not be possible, is there a way to modify the ConfigurationManager.AppSettings as seems to happen with the ConfigBuilders?
ConfigurationManager.AppSettings is readonly at the point I'm accessing, so I cannot update it myself.
We do have an IAppSettings interface for which I have written an implementation to use the Azure App Configuration REST api. However, that means storing the secret associated with the service in the usual function app settings, rather than being able to use Managed Service Identities.
Additionally, the function runtime needs some other settings before it will even reach the point of executing any of my code, meaning that I cannot move all of the settings from the standard location.
Migrating to Azure Functions V2 is not currently feasible.

A: 1.Install pacakge Microsoft.Extensions.Configuration.AzureAppConfiguration
2.Create Function .net in VS and use the code as below:
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");
    var builder = new ConfigurationBuilder();
    builder.AddAzureAppConfiguration(Environment.GetEnvironmentVariable("ConnectionString"));
    var config = builder.Build();
    string message = config["TestApp:Settings:Messagejoey"];
    return message == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + message);
}

3.The result snapshot:

4.The package I have used:

For more details, you could refer to this article(It's also suitable for .net framework).


text:
Q: Digital PID velocity controller I have seen two differente digital PID controller so far and I don't know which one should be prefered to control the speed of a dc motor.
1.) out=out_last + Kp err + Ki sum_err + Kd (err-err_last)
2.) out=Kperr + Kisum_err + Kd*(err-err_last)
The first one seems to be very slow for a variing reference signal, but achieves a good velocity control. The second one i cannot stabilize.
Which one should normally be prefered in the implementation of a speed controller on a uC?
Edit: I found a new approach for velocity control from here: https://www.controleng.com/single-article/the-velocity-of-pid/0733c0b7bfa474fb659b259808ddc869.html
Can I implement this on a uC in the form:
$$
out_n=K_p*e_n + K_v*(e_n - e_{n-1}) + K_a*((e_n-e_{n-1})-(e_{n-1}-e_{n-2}))
$$
Where in the last term the $$e_{n-1}$$ cancels. Or how should I implement the second derivative on a uC?


text:
Q: Python how do i make list appends / extends quicker? Heyo all.
Trying to get better at python and started doing leetcode problems.
Im currently doing one, were the goal is to capture water.
Link => https://leetcode.com/problems/trapping-rain-water/
problem is; it times me out for taking too long.  My code is certainly inefficient. Afer googling around i found that .append is supposedly very slow / inefficient. So is .extend.
Cant find any obvious ways of making my code faster; hence my arrival here.
any response is much appreciated
class Solution:
    def trap(self, height: List[int]) -> int:

        max_height = max(height)
        water_blocks = 0
        for element in range(max_height):
            local_map = []
            element = element + 1
            for block in height:
                if block >= element:
                    local_map.extend([1])
                else:
                    local_map.extend([0])

            if local_map.count(1) > 1:
                first_index = local_map.index(1)
                reversed_list = local_map[::-1]
                last_index = len(local_map) - 1 - reversed_list.index(1)
                water_count = last_index - first_index - 1 - (local_map.count(1) - 2)
                water_blocks += water_count
            else:
                continue
        return water_blocks

A: Although many of your count and index calls can be avoided, the two big nested loops might still be a problem. For the outer loop, max_height can be large number and the inner loop iterates over the full list. You might need to come up with a different algorithm.
I don't have a leetcode account, so I can't really test my code, but this would be my suggestion: It iterates over the height-list only once, with a small inner loop to find the next matching wall.
class Solution:
    def trap(self, h):
        water = 0
        current_height = 0
        for i, n in enumerate(h):
            # found a "bucket", add water
            if n < current_height:
                water += current_height - n
            else: # found a wall. calculate usable height
                current_height = self.n_or_max(h[i+1:], n)
        return water

    def n_or_max(self, h, n):
        local_max = 0
        for i in h:
            if i > local_max:
                local_max = i
                # that's high enough, return n
                if i >= n:
                    return n
        return local_max

A: Here are some pointers:

*

*Do not use list.count() or list.index() (that is, try to remove local_map.count(1), local_map.index(1) and reversed_list.index(1)). The first will loop (internally) over the whole list, which is obviously expensive if the list is large. The second will loop over the list until a 1 is found. Currently you even have two calls to local_map.count(1) which will always return the same answer, so at least just store the result in a variable. In your loop over blocks, you construct local_map yourself, so you do in fact know exactly what it contains, you should not have to search through it afterwards. Just put a few ifs into the first loop over blocks.

*The operation local_map[::-1] not only runs over the whole list, but additionally copies the whole thing into a new list (backwards, but that's not really contributing to the issue). Again, this new list does not contain new information, so you can figure out the value of water_count without doing this.

*The above is really the major issues. A slight further optimization can be obtained by eliminating element = element + 1. Just shift the range, as in range(1, max_height + 1).

*Also, as written in the comments, prefer list.append(x) to list.extend([x]). It's not huge, but the latter has to create an additional list (of length 1), put x into it, loop over the list and append its elements (just x) to the large list. Finally, the length-1 list is thrown away. On the contrary, list.append(x) just appends x to the list, no temporary length-1 list needed.

Note that list.append() is not slow. It's a function call, which is always somewhat slow, but the actual data operation is fast: constant time and even cleverly amortized, as juanpa.arrivillaga writes.

A: Here's another way of looking at the problem.  This scans left to right over the bins, and at each point, I track how many units of water are dammed up at each level.  When there's a tall wall, we tally up whatever units it was damming, and clear them.  However, this still gets an "overtime" flag on the next to the last test, which has about 10,000 entries.  It takes 20 seconds on my relatively old box.
class Solution():
    def trap(self, height):
        trapped = 0
        accum = [0]*max(height)
        lastwall = -1

        for h in height:
            # Take credit for everything up to our height.
            trapped += sum(accum[0:h])
            accum[0:h] = [0]*h
            for v in range(h,lastwall):
                accum[v] += 1
            lastwall = max(lastwall,h)

        return trapped

print(Solution().trap([0,1,0,2,1,0,1,3,2,1,2,1])) # 6
print(Solution().trap([4,2,0,3,2,5])) # 9


text:
Q: QDockWidget change background color when floating I have a QDockWidget with a transparent background, but I would like to change the background color or background image when it is floating. It doesn't look like the qt style sheets have a pseudo state to tell you whether or not they are floating, so I'd like to know: is this possible to do?

A: Found the solution. Add the following connection in the code:
    connect(knobDock, &QDockWidget::topLevelChanged, [&] (bool isFloating)
    {
        if (isFloating)
        {
            setAttribute(Qt::WA_TranslucentBackground, false);
            setAttribute(Qt::WA_NoSystemBackground, false);
        }
    });

This will cause the dock widgetto use whatever background is specified in the stylesheet when the dock is floating, but it will be transparent (i.e. show the mainwindow background) when it's docked.

A: You can use custom properties to do this.
Thanks @phyatt for link to Dynamic Properties and Stylesheets.
To declare custom property in your custom class you can write in .cpp:
setProperty("customPropertyName", 1);

or in .h (don't forget to define and implement used get/set access methods too):
Q_PROPERTY( int customPropertyName, READ getCustomPropertyName, WRITE setCustomPropertyName);

And in your global stylesheet file you can use the state of your custom property as following:
.YourClass[customPropertyName="1"] {
    background-color: transparent;
}

.YourClass[customPropertyName="2"] {
    background-color: black;
}

Also it's needed to reload stylesheet of the object instance after your set new property value, because stylesheets are not recalculated automatically:
object->style()->unpolish(tstFrame);
object->style()->polish(tstFrame);
object->update();

or:
object->setStyleSheet("/* */");


text:
Q: подключение одинаковых скриптов несколько раз head и footer расположены в отдельных файлах... из каждого из этого файла подключается одинаковый скрипт <script type="text/javascript" src="xyz.js"></script>, так же, в теле может быть подключение этого же скрипта еще из нескольких мест... скажите, играет ли это большую роль? это касается также и php-файлов - include(). такое массовое подключение одинаковых скриптов

A: Подключение скрипта несколько раз приводит к его повторному выполнению. Ясно, что это может привести к неприятным побочным эффектам.
Например, если данный скрипт привязывает какое-то действие к нажатию на определенный элемент, при нажатии это действие выполнится несколько раз. Вряд ли вы этого хотите.
Что касается PHP все намного проще. Вы можете спокойно подключать скрипт в любых местах не задумываясь о том, что он подключится несколько раз. Для этого вместо include() следует использовать функцию include_once().
Из документации:

Выражение include_once включает и выполняет указанный файл во время
  выполнения скрипта. Его поведение идентично выражению include, с той
  лишь разницей, что если код из файла уже один раз был включен, он не
  будет включен и выполнен повторно. Как видно из имени, он включит файл
  только один раз (include once).


text: Q: Flutter local_auth , I want to get fingerprint signature so I can encrypt it with password Is there a way to obtain a unique fingerprint signature of the user using the local_auth package (Flutter/Dart) so that I can encrypt it along with a password and store it? (Reference: https://pub.dev/packages/local_auth/example)


text:
Q: Why publish .NET Core 2.1 Self-Contained Deployment with Configuration of Release is saved to Debug? I'm publishing my first .NET core app and I'm trying to do it with self-contained deployment so users can just use the app without installing anything else.
Everything is working ok but when I use this profile

I see the following output:
2>App -> C:\Users\ido.ran\Documents\dev\App\bin\Release\netcoreapp2.1\win-x64\ParametersEditor2.dll
2>App -> C:\Users\ido.ran\Documents\dev\App\bin\Debug\netcoreapp2.1\publish\
2>App was published successfully to bin\Debug\netcoreapp2.1\publish\

Why is the deployment published to bin\Debug instead of bin\Release?

A: The Publish Wizard will publish the files to the selected 'Target Location'.

If you would like to publish it to a different location, just change this location.


text:
Q: How to get largest file in directory in bash? I have a following question. In variable DIR there is unknown number of files and folders. I would like to get the name and size in bytes of the largest one in following order: name size. For example: file.txt 124.
I tried:
cd $DIR
du  -a * | sort | head -1

But it does not show the size in bytes, and it is in size name format. How can I improve it please?

A: This should do the trick:
ls -larS | awk -F' {1,}' 'END{print $NF," ",$5}'
LS long listing reverse sort by Size, then Awk prints the last field $NF, and the 5th field, using a single space or multiple single spaces, as the field separator, of the last line, being the largest size (due to reverse sort order above).
Edit:
It was mentioned a space in the file name might cause an issue, my first suggestion, is dont use spaces in filenames, it is just plain wrong, but if you have to:
ls -larS | awk -F' {1,}' 'END{for (i=9; i<=NF; i++) printf $i" "; print " ",$5}'
will handle the space, or two, or three, or how ever many

A: What about the following pipeline? I'm using GNU findutils and GNU coreutils. If you work on a Mac you might have to install them.
find -maxdepth 1 -type f -printf '%s %f\0' \
  | sort -z -k1,1nr \
  | head -zn1 \
  | cut -zd' ' -f2-

Explanation:
find -maxdepth 1 -type f -printf '%s %f\0'

Find files in the current folder and print them along with their filesize in bytes, zero terminated. Zero terminated because filenames may contain newlines in UNIX.
sort -z -k1,1nr

Sort the listing by the filesize in bytes, column 1, in reverse order  (largest first). -z reads input zero terminated.
head -zn1

prints the first item, which is the largest, after the previous sorting. -z reads input zero terminated
cut -zd' ' -f2-

Cut off the filesize, print only the filename. -z reads input zero terminated.

A: A variation which should produce the exact output requested:
find -maxdepth 1 -type f -printf "%f %s\0" \
  | sort -znr -k2 \
  | head -zn1 \
  | tr "\0" "\n"


text:
Q: Soundcloud windget setVolume not working at all Soundcloud widget is a great thing but volume control is completely broken. JS api calls to setVolume just ignored by player, tested in latest Chrome and Firefox.
Broken volume control can be easily seen at official playground page - https://w.soundcloud.com/player/api_playground.html
Some time ago there was workaround - SoundCloud Widget API setVolume Method broken? - but now even this hack does not work. Please fix widget API. without volume control it is almost unusable ( Btw, workaround is not ok anyway, since first second of loaded sound still playing at full volume, hiting site visitor with "overloaded" sound

A: UPDATE: Just found the reason.
Seems like setVolume/getVolume range is now 0..1, not 0..100 as it was earlier
Documentation and playground just didn`t updated yet


text:
Q: Is $4k$ the best bound to ensure that a graph with $d(G)\ge 4k$ has a bipartite subgraph $H$ with $\delta(H)\ge k$? It's known (and it's a nice exercise in Diestel's book) that every graph $G$ with $d(G)\ge 4k$ (where $d(G)$ is the average degree of $G$) has a bipartite subgraph $H$ with minimum degree $\delta(H)\ge k$.
My question is: Is $4k$ the best bound known?


text:
Q: How to fill a array with numbers only from 0 to 20 C Language I need to make a C program that asks the user to insert 5 numbers into an array, but those numbers can only be from 0 to 20 if they are bigger than 20 or smaller than 0 there needs to be an error message. I'm brando new to C, so I'm having a bit of trouble getting this done and currently i have no idea how to do it. This is my current code.
int i;
int media=0;
int soma=0;

int notas[5]
for ( i=0; i <5; i++)
{
    printf("\n Por favor insira : \t");
    scanf("%f", &notas[i]);
}

if (notas[i] < 0 || notas[i] > 20)
{
    printf("\n Por favor insira um numero de 0 a 20");
}
else
{
    soma = notas[i]+notas[i];
    media = soma/5;
}

return 0;

A: You're mis-using the i variable: After the end of the loop, its value is 5 - so you're looking at the out-of-range index 5 into the notas array - which isn't what you wanted.
You should:

*

*Move your check (if notas[i] < 0 etc.) into the body of the loop.

*Repeat the i'th iteration if you got an invalid value.

Also, you seem to be mis-calculating the average value.


text:
Q: Applet is not working in browser I try launch Applet in browser, but it is now working.
In AppletViewer everything is ok.
I coppied file .html to scr folder, and try to open them, I get a ClassNotFoundException saying that PlanZajecJavaProjektApplet.class can't be found:

Code from html file

   <TITLE>Applet HTML Page</TITLE>

Applet HTML Page

<APPLET codebase="classes" code="PlanZajecJavaProjektApplet.class" width=350 height=200></APPLET>

Generated by NetBeans IDE

Code from java file:
import java.awt.GridBagConstraints;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JButton;
import javax.swing.JTextArea;

public class PlanZajecJavaProjektApplet extends javax.swing.JApplet {
...

A: My mistake, I moved to build\classes folder, where I have my class file, and now I have this:

A: When I run java applets, I put the .class files in the same folder that the .html is. When you do this, dont use the codebase='classes', because it means that your class files is located in a folder called 'classes' and it wont work.


text:
Q: PHP foreach() loop then Insert Single Array Value to MySQL DB with Submit Button After json_decode() I run a foreach() loop to display all the json results along with a submit button for each result. I wrote a mysql INSERT block to post the json results. I'm trying to figure out how to assign each json result a unique ID so that after I click the submit button, that JSON object gets posted properly to my database. What is happening currently with my code, is only the last value in the array is getting posted and not the value that I am trying to submit.
I've tried iterating over the foreach() loop and using the iterator as an assigned unique ID. Didn't work. I tried creating checkboxes next to the submit buttons and this did not work out either. I'm not sure if it's my code placement or why I'm only able to post the last value in the array.
<?php

$curl = curl_init();

$provider_first_name = 'Henry';
$provider_last_name = 'Lee';
$provider_state = 'CA';
$provider_postal_code = '';

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://npiregistry.cms.hhs.gov/api?first_name=". $provider_first_name . "&last_name=" . $provider_last_name . "&state=" . $provider_state . "&postal_code=" . $provider_postal_code . "",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",

));

$response = curl_exec($curl);

$json = json_decode($response, TRUE);

/** 10 Henry Lee Results Will Display from foreach() Loop **/
$i = 0;

foreach($json['results'] as $doc){
/** JSON Responses Listed Below **/

  $p_name = $doc['basic']['first_name'] . " " . $doc['basic']['last_name'] . ", " . $doc['basic']['credential'];

  $p_npi = $doc['number'];

  $p_address_one = $doc['addresses'][0]['address_1'];

  $p_address_two = $doc['addresses'][0]['city'] . ", " . $doc['addresses'][0]['state'] . " " . $doc['addresses'][0]['postal_code'];

  $p_skills = $doc['taxonomies'][0]['desc'];

  $p_phone = $doc['addresses'][1]['telephone_number'];

  if(empty($doc['addresses'][1]['telephone_number'])){

    $p_phone = 'Not Available';
  }

  //** Echo Each Array Value In Bordered Card **/

  echo "

              $p_name

               NPI Number: $p_npi

               $i

                $p_address_one

               $p_address_two

                $p_phone

                $p_skills

             <form action='' method='post' id='".$json['results'][$i]."'>

                     <button class='btn btn-pink btn-sm' name='add_doc' type='submit'> Add Provider</button>

             </form>

       ";
       $i++;

 }
?>

<?php

  if(isset($_POST['add_doc'])){

    $add_doc = "INSERT INTO user_posted_providers (user_id, provider_name, provider_npi, provider_address_one, provider_address_two, provider_phone, provider_skills, created_at) VALUES ('$user_id', '$p_name', '$p_npi', '$p_address_one', '$p_address_two', '$p_phone', '$p_skills', NOW())";

    $run_doc = mysqli_query($connection, $add_doc);

    if($run_doc){
      echo "";
      echo "";
    }

  }

?>

I'm trying to insert the proper array values with my 'add_doc' button in the foreach() loop, but I only able to insert the last value in the array.

A: So, might be easier to explain with some code that is just a little bit simplified. I want to show you how to present the user with the form to make their selection, then use those selected values when the form is submitted.
Sounds like you understand the concept for the most part. Guess I am not clear where you got stuck. Let's look at this code using checkboxes and one form. Understand what I have shared, try and implement it, let me know where/if you stall.
<?php
//simplified proof of concept...

//your cURL stuff would be here...
$json['results'] = [
    [
        'title' => 'Title A',
        'someIdNumber' => '123'
    ],
    [
        'title' => 'Title B',
        'someIdNumber' => '456'
    ],
    [
        'title' => 'Title C',
        'someIdNumber' => '111'
    ]
];
//...

//Has user submitted their selection? If so handle it
if (!empty($_POST)) {
    //var_dump($_POST);
    /*
    If I check the last two I'd get back the following:
    array (size=1)
      'itemId' =>
        array (size=2)
          456 => string 'on' (length=2)
          111 => string 'on' (length=2)
     */

    //now, loop on the 'results' if in our 'selection'  then do the insert, otherwise skip and check next record...
    foreach($json['results'] as $doc) {
        if (array_key_exists($doc['someIdNumber'], $_POST['itemId'])) {
            echo "selected id: {$doc['someIdNumber']}";
            //in set, do the insert here...
            //$sql = ''....
        } else {
            echo "NOT A selected id: {$doc['someIdNumber']}";
        }
    }

    return; //->
}

//if user has NOT submitted their selection, then render the form...

echo '<form method="post" action="">';
foreach($json['results'] as $doc) {
    echo "

{$doc['title']}

            <input type='checkbox' name='itemId[{$doc['someIdNumber']}] />';

        ";
}

echo '
<button type="submit" value="submit">Add Selected</button>';
echo '</form>';

Using the actual ID provided is better than using some count in the loop because there is no real guarantee the results returned by this service will be the same rendering the form as they are when processing the form submission. HTTP being a stateless protocol and all that.


text:
Q: Prevent NSTableRowView from changing highlight when not in focus? I've got an NSSplitView with a table view in the left pane. I've noticed that when I have an item selected in the left pane and I change focus to the right pane, the left pane loses focus and the highlighted row's highlight color turns to gray and the text turns black.
I have overridden the highlight color by overriding drawSelectionInRect in NSTableRowView. By doing this, the highlight color remains the same custom color, but the text turns dark which looks wrong.
Can I either let the highlight color change when the table view is out of focus, or prevent the text from turning dark when it's out of focus?

A: It appears that OS X calls setBackgroundStyle on the row view and its subviews when you click on the other view in the split view. Interestingly it seems to only happen to NSOutlineView.
Since I have code in place already to handle changing my images to different images when rows are selected (for improved contrast), and I am explicitly setting the background style when I need to using outlineViewSelectionDidChange and outlineViewSelectionIsChanging I overrode setBackgroundStyle to be a no-op and I made my own custom setter which changed the _backgroundStyle ivar.
It looks like this:
@implementation TextFieldWithHighlighting
@synthesize backgroundStyle = _backgroundStyle;
- (NSBackgroundStyle) backgroundStyle {
    return _backgroundStyle;
}
@synthesize secretBackgroundStyle = _secretBackgroundStyle;
- (NSBackgroundStyle) secretBackgroundStyle {
    return _backgroundStyle;
}

- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle {

}

- (void) setSecretBackgroundStyle:(NSBackgroundStyle)secretBackgroundStyle {
    _backgroundStyle = secretBackgroundStyle;
    self.needsDisplay = YES;
}

- (void)drawRect:(NSRect)dirtyRect {
    if(_backgroundStyle == NSBackgroundStyleDark) {
        if(self.originalTextColor == nil) {
            self.originalTextColor = self.textColor;
        }
        self.textColor = [NSColor whiteColor];
    } else {
        if(self.originalTextColor) {
            self.textColor = self.originalTextColor;
        } else {
            self.textColor = [NSColor colorWithCalibratedRed:0x40/255.0 green:0x40/255.0 blue:0x41/255.0 alpha:0xFF/255.0];
        }
    }
    [super drawRect:dirtyRect];

}

@end

It only works for me because I am explicitly handling rows changing their selection and AFAIK I am not relying anywhere on the OS changing it for me. If I could do it again I'd just push for using the system highlight color in which case I get this functionality for free.

A: Just as a small contribution to your answer. This works as well with the weird contrast generated with the drawSelectionInRect implementation. Here's a Swift solution that also works implemented in an NSTableCellView:
    override var backgroundStyle: NSBackgroundStyle {
             get {
                 return self.backgroundStyle
            }

             set {

            }
        }


text:
Q: Add sumifs function to VBA My current excel workbook consists of stock trading data which is entered into the file at the end of each day. Each day's trading activity is put onto its own individual worksheet, and the columns table layout remain consistent throughout as its the same data fields being entered every day. My current VBA provides a sum total of certain columns on all worksheets when activated and sends the active worksheet out in an email.
However, I currently have to do a manual sumif input to sum certain data points from certain columns at the end of each day. Is there a way to incorporate the sumifs formula into vba? I have no idea how to approach this but it would be an incredibly useful tool. My macro is included below, and any suggestions guidance on how to do this would be greatly appreciated.
Sub AutoSum()
Dim wscount As Long
Dim i As Long
     wscount = ActiveWorkbook.Worksheets.Count
 For i = 1 To wscount
Sheets(i).Select
Range("K4").Select
 Selection.End(xlDown).Select
ActiveCell.Offset(2, 0).Select
Dim cel1 As String, cel2 As String
cel1 = ActiveCell.Offset(-2, 0).End(xlUp).Address
cel2 = ActiveCell.Offset(-1).Address
ActiveCell.Value = "=sum(" & (cel1) & ":" & (cel2) & ")"
Next i

'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    Set rng = Nothing
    On Error Resume Next
    'Only the visible cells in the selection
    Set rng = Selection.SpecialCells(xlCellTypeVisible)
    'You can also use a fixed range if you want
    'Set rng = Sheets("YourSheet").Range("D4:D12").SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
    End If

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = "nabil.hure@dnb.no"
        .CC = ""
        .BCC = ""
        .Subject = "Today's Trades" & Date
        .HTMLBody = RangetoHTML(rng)
        .Send   'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False


text:
Q: How do I get a sticky footer? I know there have been plenty of questions regarding sticky footers, but I can't seem to get them to work on my page.
Can anyone help me make my footer sticky, not fixed?
My HTML

My CSS
#container {
    width: 980px;
    min-height: 100%;
    margin-left: auto;
    margin-right: auto; }

#content {
    width: 100%;
    min-height: 100%;
    margin: 40px 0;  }

#footer {
    width: 3000px;
    min-height: 185px;
    background-color: rgb(0,173,239);
    margin-left: -1000px;  }

I have tried various positions (relative, fixed etc) but it doesn't work. I seem to get my footer fixed and covering content. Any suggestions?

A: Try this CSS:
body {
    min-height: 100%; }

#container {
    width: 980px;
    min-height: 100%;
    margin-left: auto;
    margin-right: auto; }

#content {
    width: 100%;
    min-height: 100%;
    margin: 40px 0;
    margin-bottom: 290px;  }

#footer {
    width: 100%;
    min-height: 185px;
    background-color: rgb(0,173,239);
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;  }


text:
Q: c++ vector object address and data address confusion I created a vector a and tried to display &a and &a[0].The addresses are very different. Isn't object address usually the same as first element address? And Isn't the object memory contiguous? And I noticed the address difference between &a+1 and &a is exactly the same size of the whole vector elements, 12 bytes in this case. It looks like a copy of the whole vector to me.
#include <iostream>
#include <vector>

using namespace std;

int main(){

    vector<int> a ={3,5,8};
    cout<<"vector object address: "<<&a<<endl;
    cout<<"vector object address +1: "<<&a+1<<endl;
    cout<<"vector data[0] address: "<<&a[0]<<endl;
    cout<<"vector data[1] address: "<<&a[1]<<endl;

    return 0;

}

Can anyone explain to me how vector object works? Below is the code output:
vector object address: 0034FEBC
vector object address +1: 0034FEC8
vector data[0] address: 007D8208
vector data[1] address: 007D820C

A: The explanation of what you're seeing is that std::vector doesn't follow the same rules of array decaying like a raw c-style array does:
#include <iostream>
using std::cout;
using std::endl;

int main() {

    int a[] ={3,5,8};
    cout<<"raw array object address: "<<&a<<endl;
    cout<<"raw array object address +1: "<<&a+1<<endl; // adds sizeof(a)
    cout<<"raw array data[0] address: "<<&a[0]<<endl;  // same as a + 0
    cout<<"raw array data[1] address: "<<&a[1]<<endl;  // same as a + sizeof(int)
}

Outputs:

raw array object address: 0x7ffd02ca2eb4
raw array object address +1: 0x7ffd02ca2ec0
raw array data[0] address: 0x7ffd02ca2eb4
raw array data[1] address: 0x7ffd02ca2eb8

See live demo

Can anyone explain to me how vector object works?

A std::vector instance is a non POD variable, and will have it's own address at the local storage. It merely wraps the underlying memory address that is actually used to store the data. How exactly is implementation defined, but you can consider that there's at least an interned pointer, and an allocator concept is used to obtain the memory.
Keeping track of the current size, and copying to reallocated memory is managed as well.
The std::vector::data() functions are dedicated to access that guaranteed contiguous chunk of memory.
You should notice that the pointers you obtain through the mentioned data() functions aren't stable, and may get invalidated as soon the std::vector is manipulated in a way.

Also worth mentioning that std::array makes an exception here from the other standard containers:
#include <iostream>
#include <array>

using std::array;
using std::cout;
using std::endl;

int main() {

    array<int,3> a ={3,5,8};
    cout<<"std::array object address: "<<&a<<endl; // Note these addresses ...
    cout<<"std::array object address +1: "<<&a+1<<endl;
    cout<<"std::array data[0] address: "<<&a[0]<<endl; // are the same
    cout<<"std::array data[1] address: "<<&a[1]<<endl;
}

Outputs:

std::array object address: 0x7ffe72f1cf24
std::array object address +1: 0x7ffe72f1cf30
std::array data[0] address: 0x7ffe72f1cf24
std::array data[1] address: 0x7ffe72f1cf28

Live demo

A: A vector consists of two parts. One is the object itself, and it is fixed size. The other is the data contained within the vector, and it is variable. One of the members of the vector object will be a pointer to the data contained by the vector. &a returns a pointer to the vector object, and &a[0] returns a pointer to the data which is not in the same place as the object.
&a gives you the pointer to the vector object. You're using pointer arithmetic when you do &a+1, which would give you a pointer to the next vector in an array of vectors. Since you don't have an array, &a+1 is returning an invalid pointer, but C++ doesn't have any way of knowing that.

A: How the vector works is implementation defined. However they are required to store their elements dynamically on the free store by default. This means when you create a std::vector it then gets the memory for its members separately.
It could be implemented something like this:
template<typename T>
class vector
{
public:

    // The returned element will not have the same address as this
    T& operator[](std::size_t n) { return m_begin[n]; }

private:
    T* m_begin; // start of internal array
    T* m_top;   // end of contained elements
    T* m_end;   // end of internal array
};

Note: Crucial parts missing from the above mockup
The address of the element is stored directly in the vector object, not the elements themselves.


text:
Q: PHP not detect GET language from rewrite url I have this multi language rewrite url from .htaccess:
RewriteEngine On
RewriteBase /pms/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^((fr))/([A-Za-z0-9-]+)/([0-9]+)/([A-Za-z0-9-]+)/?.html$ article.php?page=$3&id=$4&title=$5$lang=$1 [NC,L,QSA]

in article.php page I need to print fr from $_GET['lang']. But i see blank and not detect $_GET['lang']:
$lang = isset($_GET['lang']);
echo $lang;

how do can i print lang name from rewrite url?!

A: seems like there is a $ before lang
try
article.php?page=$3&id=$4&title=$5&lang=$1

A: article.php?page=$3&id=$4&title=$5$lang=$1

it should be used like this
article.php?page=$3&id=$4&title=$5&lang=$1

And Also isset  Determine if a variable is set and is not NULL so it will return as true or false
 $lang = isset($_GET['lang']);
    echo $lang;

$lang contains true or false not name of lang use this like
if(isset($_GET['lang']))
{
 $lang = $_GET['lang'];
 echo $lang;
}


text:
Q: paralleling switching regulators If one has to design a boost power supply that should generate high output current, it can be a solution to parallel multiple boosters and connect their output nodes to each other. Does this approach have any problems?
Many booster ICs have SYNC pins so that multiple regulators can be synchronized with each other using an external clock generator. The boosters would have ripples in the output voltage, but the amplitude should be small.
I know that there is a method called "load sharing" or "current sharing". But I wonder why it is needed.

A: It is possible to do, but it is not as simple as you think.
First comes the switching frequency. If you have several regulators interacting, beat frequencies and resonances can occur. As you mention some modules/regulators have synchronization inputs and/or outputs that would fix this issue.
Then comes load sharing. Whatever module has the highest output voltage will take the brunt of the load while the other regulators attempt to reduce their output. A small series resistor on each might help equalize the loads somewhat, but this will waste power and reduce load regulation.
And last, but most importantly, comes regulation feedback loop stability. The interaction of multiple similar feedback loops fighting with each other, makes an overall unstable and chaotic system very likely, which could result on EMC problems, output oscillation problems, or even the destruction of the modules themselves or the attached circuitry.
Some modules/regulators have been designed to be ganged together. These will normally have a "share" connection that allows their control algorithms to cooperate for equally sharing the load. Others can be made to cooperate with a vendor-approved method that is provided in their datasheets.


text:
Q: How to make NSStringDrawingContext shrink text? I'm trying to use the attributed string API of iOS 6 to calculate the size of text and shrink the font size if necessary. However, I can't get it to work as the documentation says.
NSString *string = @"This is a long text that doesn't shrink as it should";

NSStringDrawingContext *context = [NSStringDrawingContext new];
context.minimumScaleFactor = 0.5;

UIFont *font = [UIFont fontWithName:@"SourceSansPro-Bold" size:32.f];

NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.lineBreakMode = NSLineBreakByClipping;

NSDictionary *attributes = @{ NSFontAttributeName: font,
                              NSParagraphStyleAttributeName: paragraphStyle };

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.title attributes:attributes];

CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(512.f, 512.f) options:NSStringDrawingUsesLineFragmentOrigin context:context];

NSLog(@"rect: %@, context: %@", NSStringFromCGRect(rect), context.debugDescription);

But the text doesn't shrink and is truncated. actualScaleFactor is always 1. The log results are:
rect:{{0, 0}, {431.64801, 80.447998}}, context:<NSStringDrawingContext: 0x14e85770> minimumScaleFactor:0.500000 minimumTrackingAdjustment:0.000000 actualScaleFactor:1.000000 actualTrackingAdjustment:0.000000 totalBounds:{{0, 0}, {431.64801, 80.447998}}

The result is the same if I use the actual drawing method and not the measuring method. If I remove the paragraph style, it makes the text wrap and doesn't shrink it. If I remove the paragraph style AND I choose a size that only allows one line of text, the text is truncated too instead of being shrunk. What is wrong? There is very little documentation or online resources dealing with NSStringDrawingContext. And I'm trying to avoid the use of sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode: which is deprecated in iOS 7.

A: After googling for a long time I did not find a solution working under iOS7. Right now I use the following workaround, knowing that it is very ugly. I render a UILabel in memory, take a screenshot and draw that. UILabel is able to shrink the text correctly.
But perhaps someone finds it useful.
    UILabel *myLabel = [[UILabel alloc] initWithFrame:myLabelFrame];
    myLabel.font = [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:16];
    myLabel.text = @"Some text that is too long";
    myLabel.minimumScaleFactor = 0.5;
    myLabel.adjustsFontSizeToFitWidth = YES;
    myLabel.backgroundColor = [UIColor clearColor];

    UIGraphicsBeginImageContextWithOptions(myLabelFrame.size, NO, 0.0f);
    [[myLabel layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [screenshot drawInRect:myLabel.frame];

A: NSStringDrawingContext's minimumScaleFactor appears to be broken in iOS 7.
As far as I can make out, even in iOS 6, it didn't work for drawing; it worked for measuring, so you could work out what would happen in a context where it does work for drawing, like a UILabel. That way, you know the correct minimum height for the label.
Or, you could use the resulting scale factor to shrink the text yourself, in the knowledge that now it will fit.
Example:
- (void)drawRect:(CGRect)rect
{
    // rect is 0,0,210,31

    NSMutableAttributedString* s =
        [[NSMutableAttributedString alloc] initWithString: @"This is the army Mister Jones."];
    [s addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"GillSans" size:20]}
        range:NSMakeRange(0,s.length)];

    NSMutableParagraphStyle* para = [[NSMutableParagraphStyle alloc] init];
    para.lineBreakMode = NSLineBreakByTruncatingTail;
    [s addAttributes:@{NSParagraphStyleAttributeName:para}
        range:NSMakeRange(0,s.length)];

    NSStringDrawingContext* con = [[NSStringDrawingContext alloc] init];
    con.minimumScaleFactor = 0.5;

    CGRect result =
        [s boundingRectWithSize:rect.size
            options:NSStringDrawingUsesLineFragmentOrigin context:con];
    CGFloat scale = con.actualScaleFactor;
    // ...(could have a check here to see if result fits in target rect)...

    // fix font to use scale factor, and draw
    [s addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"GillSans" size:20*scale]}
        range:NSMakeRange(0,s.length)];
    [s drawWithRect:rect options:NSStringDrawingUsesLineFragmentOrigin context:nil];

}

In iOS 6, scale is about 0.85 and you can use it as shown to shrink the text. But in iOS 7, scale remains at 1, suggesting that no shrinkage is happening and this feature of NSStringDrawingContext is now useless. I can't tell whether that's a bug or whether the feature has been deliberately abandoned.

A: Just wanted to post this solution as I have been battling with this for a couple hours. I could never get the text area to scale down and would always have the last lines of text cut off.
The solution for me was to not add a context and just set it to nil. I got this when looking at the example on this site. https://littlebitesofcocoa.com/144-drawing-multiline-strings
Note after getting the size the box would draw at using
pageStringSize = [myString boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrsDictionary context:nil];

I still needed to loop through scaling down the font manually:
while (pageStringSize.size.height > 140 && scale > 0.5) {
            scale = scale - 0.1;
            font = [UIFont fontWithName:@"Chalkboard SE" size:24.0 *scale];
            attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,[NSNumber numberWithFloat:1.0], NSBaselineOffsetAttributeName, nil];

            pageStringSize = [myString boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrsDictionary context:nil];

        }


text:
Q: How would the action url of an html form appended to a new window in javascript change? I want to send a popup to a user if the user is not logged into my forum.
So far it works as far as appending the HTMl form to the new window created in Javascript; however, when I press the actual submit forms via the new window I get the basic 404 even though I use absolute URLs.
Here's the basic Javascript:

...and here's a basic link to a test page http://www.sportsboard.netai.net/Scripts/login.php?test=yes
If you press the submit buttons on there you'll be redirected to my testing free host's 404 page not found.
How do I make the form submit as if it were on a regular page?

A: My guess would be you are using absolute urls incorrectly. Since, you didn't prefix your form post action with http://www. it is attempting to post it to the local relative path. Try this:
action="http://www.sportsboard.netai.net/page.php?page=register&&do=register&&formdisplay=false"

A: The answer is as sctskw said! The action tried to search for the URL locally, so I added the http://www. to correctly direct the URL.


text:
Q: Finding the angle of rotation relative to a normal of a 2D image with TensorFlow I am new to TF, so what is the general process of finding the angle of a 2D image? What I want to do is find the angle of rotation a particular object real-time.
Here's an example of what I am trying to achieve:

and every angle in between (to at least .1 angle).
I am assuming that I might need to detect the base image (angle=0) then compare any other rotated images to it?


text:
Q: Find and Delete a Folder when it has a specfic parent folder I'm trying to search and delete an old Backup of a program on a 4TB Disk. There may well be over 500 instances of it for various users, etc... The folder is called ACCOUNTS and it is located in /home/local/*/backups/Acc/ACCOUNTS where * is a username. The problem is that the most recent backups are located in /home/local/*/backups/Acc/Mon/ACCOUNTSfor 7 day rotations.
I can use find to find and delete all instances of ACCOUNTS but this will delete the ones I want to keep also.
So how would have search for a Folder called Accounts whos Parent folder is call Acc and delete it while leaving all other instances of ACCOUNTS intacted?
I tried find /home/local/ -type d -name "Acc/ACCOUNTS" -exec rm -rf {} \; but this will not work because it will think the the forward slash is part of the name and give a warning.

A: rm -r /home/local/*/backups/Acc/ACCOUNTS

should work. Or if you have a lot of accounts and the above hits ARG_MAX
for f in /home/local/*/backups/Acc/ACCOUNTS; do rm -r "$f"; done

You can test what it's going to delete by just doing echo home/local/*/backups/Acc/ACCOUNTS
If for some reason you want find, you can do a number of different things, probably simplest would be just to use -regex
find /home/local/ -type d -regex '.*/Acc/ACCOUNTS' -exec rm -rf {} \;

Replace -exec rm -rf {} \; with -print to test.


text:
Q: Using .Net to authenticate against Active Directory when disconnected I have a .Net client WPF application using System.DirectoryServices and LDAP for authentication.  On start of the app, I want to force users to re-authenticate using their domain account (which is how they logged into windows).  I understand I can use the following to perform the authentication when a connection is available.
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain,
            userName, password);

The wrinkle is that the application is at times used by remote users who may not have a connection.  Windows itself still allows domain users to sign on even when disconnected.  Is there a similar means of authenticating users in a disconnected environment using the .Net Framework?

A: If there is no connection, there is no connection. Windows maintains a cached version of the last login for that user (meaning a new user would not be able to log into a machine with no connection to the domain). You can use the local system authentication to find out which user is using the system and determine local cached permissions based on that. These methods would still be located within the System.DirectoryServices namespace, the location for parsing the query would change though (and I don't believe it'll accept LDAP queries locally).
Edit:
You can also find some classes with in the System.Security / System.Security.Permissions namespaces that will facilitate these needs.

A: Believe I found a way to do this using the LogonUser function of advapi32.dll.
 Dim tokenHandle As New IntPtr(0)
 Const LOGON32_PROVIDER_DEFAULT As Integer = 0
 Const LOGON32_LOGON_INTERACTIVE As Integer = 2
 tokenHandle = IntPtr.Zero
 Dim returnValue As Boolean = LogonUser("<username>", "<domain>", "<password>", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle)

 Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
                        ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
                        ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
                        ByRef phToken As IntPtr) As Boolean

When disconnected this appears to validate against the local cached version of the last log on.


text: Q: Is there a stochastic AdaBoost? In sklearn, the AdaBoostClassifier and AdaBoostRegressor classes do not have the subsample and max_features parameters, which are responsible for the stochastic approach to building a boosting model. Question: is it possible to build stochastic adaptive boosting at all?


text:
Q: Labeling line twice based on direction in QGIS TL;DR: I would like to put two labels on the same line as on the picture below.
I have three layers:

*

*Points: `"Point_ID""

*Lines: `"Line_ID""

*Label table (non-spatial): "ID", "Line_ID", "Start_point_ID", "End_point_ID", "Label"
Some of the lines are referenced twice in the Label table but with different directionality. I would like to label my lines based on the label direction in the label table, just like on the picture below.

My question is how could I achieve this?
I know I could duplicate the line feature and add an extra attribute based on the joined Label layer with the values like "forward", "backward" but I would like to stay with one line layer.
Is it maybe possible to use geometry generator tool in QGIS? I have the Point_ID-s if I join the Label layer. (I don't seek complete solution to my problem. I just need some guidance.)
Or is there a way more easier way I don't know about? A plugin for example?

A: Instead of single labels, use rule-based labeling and create two rules, one for the label this way, the other for the label that way.

For the second one, in placement tab, activate Geometry generator with this expression to change the line direction: reverse($geometry) and be sure to have checked the box Line orientation dependent postion (screenshot 1).
On the placement tab, activate Show upside-down labels by selctign always (screenshot 2).

A: A way would be something like this (not tested with real data/layers):
CREATE TABLE IF NOT EXISTS Lines_with_label AS
SELECT
lns.geometry, lbl.Label
FROM Label_table AS lbl
JOIN Lines_layer AS lns
ON lns.Line_ID = lbl.Line_ID
WHERE
ST_StartPoint(lns.geometry) =
    (SELECT Points.geometry from Points WHERE Points.Point_ID = lbl.Start_point_ID LIMIT 1)
AND
ST_EndPoint(lns.geometry) =
    (SELECT Points.geometry from Points WHERE Points.Point_ID = lbl.End_point_ID LIMIT 1)
;

which creates a new layer only with lines which have a label associated, aond only if labels are in the correct direction (i.e. Start_point_ID is the first point of the corresponding line, and End_point_ID the last).
That should work also with polygons, BTW.


text:
Q: event data always seems to be null on onWrite I can't seem to figure out why the following log only returns an array of null values (like [ null, null, null, null, etc.]
exports.scheduleFirst =
functions.database.ref('savedPlant/{uid}/{pushId}').onWrite(event => {
   const val = event.data.val();
   console.log(val)
})

After some further research I found that the '_data'  property of event.data also has 'null' as value. However, the _newData property of event.data contains the newly added data that I'm looking for. So if I do:
exports.scheduleFirst =
functions.database.ref('savedPlant/{uid}/{pushId}').onWrite(event => {
   const val = event.data._newData
   console.log(val)
})

It actually returns the object with the data that has been added. What am I missing here?


text:
Q: AOS library and Angular, scroll animation not triggered on click on a navbar link for same page section navigation As the question implies, the scrolling animation works as intended, but when I click on a link from the navigation bar it does take me to the contact section on the same page (for example) but it does not detect a mouse scroll thus not triggering the animations on that section.
Any help or idea would be appreciated!
EDIT:
Using an Click event to scroll to the desired section from the navbar
goTo(location: string): void {
   window.location.hash = location;

   //Tried using this, but it does trigger the animation on scroll up, not on scroll down
   AOS.refresh();
}


text:
Q: ClassNotFoundException: Attempted to load class "MongoId" from the global namespace I am trying to install the MongoDB bundle into Symfony2. I followed Symfony documentation.
My config.yml file is:
doctrine_mongodb:
connections:
    default:
        server: mongodb://localhost:27017
        options: {}
default_database: test_database
document_managers:
    default:
        auto_mapping: true

My autoload file is:
use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;
$loader = require __DIR__.'/../vendor/autoload.php';

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
AnnotationDriver::registerAnnotationClasses();

return $loader;

The controller and the document/product files were exactly copied from the Symfony site (I only changed the name AcmeStoreBundle to MyTestBundle).
But when I attempt to insert data, I get the following error:
ClassNotFoundException: Attempted to load class "MongoId" from the global namespace in
C:\wamp\www\MongoTest2\vendor\doctrine\mongodb-odm\lib\Doctrine\ODM\MongoDB\Id\AutoGenerator.php line 36.
Did you forget a use statement for this class?

(I cleared the cache and tried again)
Please help me to understand what's going wrong.

A: Install composer package alcaeus/mongo-php-adapter, because it has MongoId class. This also helped for me


text:
Q: Jquery Boxy , Show one Dialog at a time Im using Boxy. I'm looking for inbuild function to open a One Dialog at a time. When I click on the button, Boxy Dialog will apper. When I again Clicked on the button, One more Same Dialog apper. I want to keep modal : false because of some reasons. I don't want to unbind the click event from element for every Dialog. it's ugly.
HTML
Edit

Jquery
cube :
{
   edit : function()
   {
          // Open Boxy Dialog
          edit_box = new Boxy("something",{ title : 'edit', modal : false });

   }

}


text:
Q: Swift 4 - 3D Touch Quick Actions With Tab Bar & Navigation Controller I am trying to add 3D Touch Quick Actions from the home screen and I am using the following code:
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabVC = storyboard.instantiateViewController(withIdentifier: "TabVC") as! UITabBarController
        let mainVC = storyboard.instantiateViewController(withIdentifier: "NavMoreVC") as! UINavigationController
        let foodVC = storyboard.instantiateViewController(withIdentifier: "FoodVC") as! FoodTableViewController
        window?.rootViewController = tabVC
        self.window?.makeKeyAndVisible()
        mainVC.pushViewController(foodVC, animated: true)

I'm trying to navigate to the Find Food view controller after the user tapped on the shortcut, but the code above gives me an error in the console:
Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x10e022600>.

Is there a way for the app to push to the Find Food view controller while maintaining the Tab Bar and Navigation Controllers. Thanks!!

A: Did some more digging and found the solution to it. I used the following code in the AppDelegate:
    let myTabBar = self.window?.rootViewController as? UITabBarController
    myTabBar?.selectedIndex = 0
    let nvc = myTabBar?.selectedViewController as? UINavigationController
    let vc = nvc?.viewControllers.first as? MoreViewController
    nvc?.popToRootViewController(animated: false)
    return vc!.openPageFor(shortcutIdentifier: shortcutIdentifier)

Then inside my MoreViewController I had a function that will call the different segues based on the shortcutIdentifier.

A: First you make the rootVC as the tab then the navigate should be from inside it
so subclass the tabBarControllber and in viewDidAppear , do the push according to navigate bool or logic shared inside your app
    let foodVC = storyboard.instantiateViewController(withIdentifier: "FoodVC") as! BusStatusTableViewController
    // here do segue to food VC


text:
Q: JSF: invoking a javascript after a successful creation my current code.
<h:form>
   <h:panelGroup id="messagePanel" layout="block">
       <h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
   </h:panelGroup>
    <h:panelGrid columns="2">

        // some form input stuff here..

    </h:panelGrid>

   <h:commandButton class="register-btn" action="#{accountController.create}" value="#{bundle.Register}">
        <f:ajax event="action" execute="@form" render="messagePanel"/>
   </h:commandButton>
</h:form>

messagePanel is where the validation errors displays.
create() method
public String create() {
        try {

            getFacadeUser().create(currentUser);

            FacesContext.getCurrentInstance().getExternalContext().redirect("/index.xhtml");
            return null;
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

is it possible to invoke a javascript after a successful creation? currently my create form is a pop up modal, what i want is to just hide the modal after a successful creation rather than redirecting to a page.
i'm using JSF 2.1

A: You can create a component binding for your dialog in your managed bean and hide the dialog from your function using that binding. I think the type of object which represents your component binding is framework specific (although all of them probably extend UIComponent), so you need to specify what JSF implementation you are using for a full solution. I implemented this very use case in ADF for example.
This is an example from ADF:
<af:popup id="sample" binding="#{viewScope.myBean.myPopup}">
and in the managed bean:

RichPopup myPopup;
    ...
public void onSave() {
    //save user
    myPopup.hide();
}

A: With standard JSF (read: no component libraries or utility libraries such as PrimeFaces or OmniFaces which have ways to make this easier), your best bet is to conditionally render <script> element.
<h:panelGroup id="script">
    <h:outputScript rendered="#{not empty accountController.currentUser.id}">
        alert('User successfully created!');
    </h:outputScript>
</h:panelGroup>

Reference it in <f:ajax ... render="script">.


text:
Q: Paralleling op-amps for more current? I'm trying to design a current source / sink that will be a part of a step generator that will drive a BJT base. I only intend to drive small BJT transistors so a max base current of 10mA was decided upon (somewhat arbitrary).
The circuit I'm using is the following one:

The circuit can be re-configured by changing the polarity of the current source to sink. Using an op-amp with ultra-high input impedance / low input bias this circuit can go to nano amps and I intend to try and get close to that.
The op-amp of choice is TI (BB) OPA128 which has a typical current out rating of +/- 10mA. This seems about right, but I am a little worried that I will be stressing the device.
I have a couple of these devices, can I simply connect two of them in parallel or some other configuration so they will be able to drive a constant current of 10mA without too much "effort"?

A: You could try an output buffer something like this:

simulate this circuit – Schematic created using CircuitLab
As well as not exceeding the op-amp output capability you probably want to minimize the self-heating to improve the accuracy. The degradation with increasing die temperature is profound, and there's no sense throwing away performance of a stupidly expensive component (of course maybe you don't need to worry about low bias current and high current simultaneously in this application).

Edit: Below is a simulation you can play with. It's 100mA. You have to keep the output from saturating- so depending on op-amp and current the output might be able get within a few volts or less of each supply bus. The op-amp is supplying 1.4mA to get 200mA of load current (the output carries both the input and output current).

simulate this circuit

A:
See the picture.  The source and drain current are the same.  I hope this helps.


text:
Q: Regular expression confusion on how to specify input How would I define a regular expression for strings from the alphabet set {a,b} where the strings only have exactly 2 as?

A: You could use something like:
b*ab*ab*

It looks something like this:

A: The usual way is a look ahead:
^(?=([^a]*a){2}[^a]*$)[ab]*$