text:
Q: What does the lack of Unicode support in PHP mean? How can the lack of Unicode support in PHP affect a PHP web app?

A: There are (at least) three different approaches to text in the modern programming world.

*

*treat text as a sequence of bytes. There is a widespread convention that byte values 0-127 represent ascii but what byte values 128-255 mean depends on the context. They may be characters in a single byte legacy character set, code units of a multibyte legacy character set or code units of UTF-8.

*treat text as a sequence of unicode code points.

*treat text as a sequence of UTF-16 code units.
In general a language and/or the libraries, APIs and protocols used with it encourage or even force a given approach.
php takes the first approach. A string is just a sequence of bytes, there is no special type for Unicode. Some would characterise this as "not supporting unicode" but I would consider that a mis-characterisation.
What is does mean is that if you are using php with utf-8 it is your responsibility to do so correctly. UTF-8 is a fairly well behaved encoding so you don't have to worry as much as you did with some legacy multibyte encodings but you still need to be careful about some operations. Especially truncation (don't want to cut in the middle of a multibyte sequence) and character counting (is a count of utf-8 code units acceptable for the given application or do you need to count code points or even something else). If you don't take responsibility for these things your users are likely to see glitches.
On the other hand it matches well with how internet protocols work. A system that works with strings as sequences of bytes can deal with internet data without encoding conversions. A system that works in seuences of code points or utf-16 code units must usually perform conversions of text going to/from the internet.

A: It means that you have to take some shortcuts and do nasty tricks in order to get unicode. And that those tricks are going to make the code more cumbersome and less readable.

A: Actually php has methods to manipulate multi byte strings - please see mbstring. There is also a configuration option in php.ini to use mbstring replacements for most (all) of the string manipulation functions - for details on that please see mbstring overload.

A: Any website that purports to be multi-lingual or to deal with documents or content that is not representable in Latin-1 is likely to be problematic if you don't have Unicode support.

*

*For example, http://amazon.jp would be toast without Unicode.

Another problematic use-case is when content might contain mathematical and other symbols.

However, your example of Facebook suggests that in fact you can in fact "do" Unicode in PHP.  Alternatively, http://facebook.jp is not implemented in PHP.  Either way, the home page says:
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

and has lots of UTF-8 content.

OK, here's what the PHP doc for "String" says:

"A string is series of characters, therefore, a character is the same as a byte. That is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some basic Unicode functionality."

So PHP does have Unicode support.  It is just that "native strings" are not Unicode based.
So what it means is that if you need to deal with any language (or set of languages) that cannot be encode in an 8-bit character set, your PHP code is going to be more cumbersome at any point where it needs to process content as (real) characters.


text:
Q: Ionic 2: Choose the .apk to run I've installed the crosswalk plugin and built my app with cordova build --release.
This generated 2 apk files: android-armv7-release-unsigned.apk and android-x86-release-unsigned.apk. Now I would like to run my app on my device using one of these apk's, but when I run ionic run android --device, it builds 2 more apks and uses android-armv7-debug.apk to run the app.
How can I choose the apk that my app needs to use ?
Thanks
Edit: here's config.xml

A: You should be running with release and prod flags.
ionic run android --prod --release

Check the link
By default it will build and run debug apks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Room+dagger 2. NPE Using Room+LiveData+Dagger2+Kotlin
db code:
@Database(entities = arrayOf(MonthlyBudget::class, Purchase::class), version = 1, exportSchema = false)
@TypeConverters(DateTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun budgetDAO(): BudgetDAO
    abstract fun purchaseDAO(): PurchaseDAO
}

Method in dagger2 which provides db
@Provides
fun providesAppDatabase(context: Context): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "my-budget-db").allowMainThreadQueries().build()

Method in dagger 2 which return null
@Provides
@Singleton
@Named("CurrentMonthBudget")
fun provideCurrentMonthBudget(repository: AppRepository): MonthlyBudget = repository.currentMonthBudget()

Object's inject
@Inject
@Nullable
@field:Named("CurrentMonthBudget")
lateinit var currentMonthBudget: MonthlyBudget

Because of the null data i getting this
java.lang.NullPointerException: Cannot return null from a non-@Nullable @Provides method

This is how i did it: created a nullcheck and If 'If' gets back 'true',  I add default values in db.
@Database(entities = arrayOf(MonthlyBudget::class, Purchase::class), version = 1, exportSchema = false)
@TypeConverters(DateTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun budgetDAO(): BudgetDAO
    abstract fun purchaseDAO(): PurchaseDAO
    companion object {
        fun getInstance(context:Context):AppDatabase {
            val database = Room.databaseBuilder(context, AppDatabase::class.java, "my-budget-db").allowMainThreadQueries().build()
            if (database.budgetDAO().queryCurrentMonthBudget() == null) {
                database.budgetDAO().insert(MonthlyBudget(0), MonthlyBudget(0))
                database.purchaseDAO().insert(Purchase("default",0))
            }
            return database
        }
    }
}

What should i do? Fill the db? If so, tell me the better way to do it, or is there another way?

A: I think you need to set the @Nullable on the provideCurrentMonthBudget. Also since this is kotlin, the return type should be MonthlyBudget? - kotlin denotes nullable types with a ?.


text:
Q: Joining multiple select sql statements (4 tables) I need to join together 2 SQL statements and both of those statements work on their own. But I don't know how to combine both into 1 SQL statement.
I have two tables in 1st statement, TR120 and TR1201.
The SQL is this:
select
    PRODUCT, PRICE, QUANTITY, INVOICE.DATE
from
    TR1201
left join
    (select
         DATE, ID as INVOICE_ID, INVOICE
     from TR120) as INVOICE on INVOICE.INVOICE_ID = ID
where
    INVOICE.DATE >= '2016-06-01' and INVOICE.DATE <= '2016-06-30'

This returns a list of all the products I sold, with price, quantity and date of sales in a specific time frame from 01-06-16 till 30-06-16.
Now I need to find out the latest price that I bought product for in different two tables TR100 and TR1001 based on the product and date of sale from the 1st SQL statement.
select
    PRODUCT, PRICE, SUP.DATE
from
    TR1001
left join
    (select
         DATE, ID as SUP_ID, SUP_INVOICE
     from TR100) as SUP on SUP.SUP_ID = ID

This returns a list of all the products that I have bought with a price and a date. I only need last record from this query based on product and date of purchased.
TR120
ID | INVOICE | DATE
1  | 000001  |2016-06-05
2  | 000002  |2016-06-15
3  | 000003  |2016-06-25

TR1201
ID | PRODUCT | PRICE A | QUANTITY
1  | A       | 2,00    |    5
2  | A       | 2,00    |    2
3  | A       | 2,00    |    1

TR100
ID | SUP_INVOICE | DATE
1  | 160001      | 2016-05-30
2  | 160002      | 2016-06-16

TR1001
ID | PRODUCT | PRICE B
1  | A       | 0,5
2  | A       | 0,7

The result I am trying to get is this:
PRODUCT | PRICE A (tr1201) | QUANTITY | DATE (tr100) | PRICE B (tr1001)
A       | 2                |  5       | 2016-05-30   |   0,5
A       | 2                |  2       | 2016-05-15   |   0,5
A       | 2                |  1       | 2016-05-16   |   0,7

That is all I want to do :(

A: Have you tried first_value?
FIRST_VALUE ( [scalar_expression ] )
    OVER ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )

it works like this:
  select distinct id,
         first_value(price) over (partition by id (,sup) order by date DESC (latest, ASC for oldest)) as last_price
 from table;

Documentation can be found here: https://msdn.microsoft.com/en-us/library/hh213018.aspx

A: I don't have your tables so cannot test and therefore am providing advice only.
I think what you need is an Outer apply like this instead of joins
select
      T1.Product
    , T1.Price
    , T2.DATE   -- Alias this
    , T2.Price  -- Alias this
    , T3.DATE   -- Alias this
    , T3.Price  -- Alias this
from T1
OUTER APPLY (
    select top 1
          Date
         ,Price
    from table2
    WHERE ID = T1.Id AND product = T1.Product-- plus any other joins
    ORDER BY Date desc
) as T2
OUTER APPLY (
    select top 1
          Date
         ,Price
    from table3
    WHERE ID = T1.Id AND product = T1.Product-- plus any other joins
    ORDER BY Date desc
) as T3


text:
Q: Implicit conversion with operator This is in part inspired by this question. When I write the code:
void test(std::string inp)
{
  std::cout << inp << std::endl;
}

int main(void)
{
  test("test");
  return 0;
}

"test" is implicitly converted from const char* to std::string, and I get the expected output. However, when I try this:
std::string operator*(int lhs, std::string rhs)
{
  std::string result = "";

  for(int i = 0; i < lhs; i++)
  {
    result += rhs;
  }

  return result;
}

int main(void)
{
  std::string test = 5 * "a";
  return 0;
}

I get the compiler error, invalid operands of types 'int' and 'const char [2]' to binary 'operator*'. "a" was not implicitly converted to std::string here, instead it remained a const char*. Why is the compiler able to determine the need for an implicit conversion in the case of a function call, but not for the case of an operator?

A: Indeed, operators have different rules from other kinds of functions.

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator
  is assumed to be a built-in operator and interpreted according to Clause 5.

([over.match.oper]/1)


text:
Q: Problem with maven test I have maven project X which depends on project Y. when I run the tests on project X, it is not able to find the test files in project Y although it is in the class path.

A: The usual convention in Maven is to have the unit tests localy to your project which means you can't use classes from outside the current project. This is coming also from the point that the test class will not be packaged into a jar in contradiction to the production code (src/main/java). But you can solve the problem by defining the class you would like to reuse like the following (project Y):
<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>test-jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
</build>

You have to do mvn install (or may be mvn deploy) and in project Y you have to use the above by defining it like the following:
<dependency>
  <groupId>${project.groupId}</groupId>
  <artifactId>test</artifactId>
  <version>${project.version}</version>
  <type>test-jar</type>
  <scope>test</scope>
</dependency>


text:
Q: Concat strings and numbers in C++? I'm trying to concat "(" + mouseX + ", " + mouseY ")".  However, mouseX and mouseY are ints, so I tried using a stringstream as follows:
std::stringstream pos;
pos << "(" <<  mouseX << ", " << mouseY << ")";
_glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str());

And it doesn't seem to work.
I get the following error:

mouse.cpp:75: error: cannot convert std::basic_string<char, std::char_traits<char>, std::allocator<char> >' toconst char*' for argument 2' tovoid _glutBitmapString(void*, const char*)'

What am I doing wrong in this basic string + integer concatenation?

A: glutBitmapString() expects a char* and you're sending it a string. use .c_str() on the string like so:
_glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str().c_str());

A: Try
_glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str().c_str());


text:
Q: Prevent download of entire remote resource with HttpClient? Under UWP, the low-level HttpWebRequest class and its ilk have been been deprecated, and the official recommendation is to use System.Net.Http.HttpClient
However, there seems to be either a glaring oversight or a bug in the the HttpClient implementation: the API does not seem to provide a way to make a request to a remote URI that does not automatically download the entire remote resource (in the case of a GET request) to allow for lazy evaluation of the response stream.
The documentation for the HttpClient.GetAsync() method says:

This operation will not block. The returned task object will complete after the whole response (including content) is read.

Which states upfront that the entire remote resource will be downloaded before the request is considered completed. There is an HttpCompletionOption parameter which would theoretically allow for working around this if HttpCompletionOption.ResponseHeadersRead is specified, as that is documented as follows:

The operation should complete as soon as a response is available and headers are read. The content is not read yet.

However, regardless of which HttpCompletionOption is specified, in all cases, HttpClient.GetAsync() appears to allocate the complete ContentLength bytes of the response (in memory! all at once! without any limit checking!) in the process. Naturally, that is somewhat insane and a real problem.
In my particular case, I just want to read the first few kb of a multi-gigabyte remote resource from a server that does not support http range headers. This is normally a "no sweat" operation: just create web request, read from the response stream until you're satisfied, then close the response and be on your merry way.
That does not seem to be an option with the default HttpClient API. Is there a simple workaround that does not involve crafting my own HTTP requests using raw sockets?

A:
in all cases, HttpClient.GetAsync() appears to allocate the complete ContentLength bytes of the response (in memory! all at once! without any limit checking!)

This is not true for the HttpCompletionOption.ResponseHeadersRead option.
Just like using the old sweet HttpWebRequest class, you can open the response stream and read a few bytes then discard the response. Here is an example.
Here is my experiment: (I use Windows.Web.Http.HttpClient instead, but System.Net.Http.HttpClient provides similar APIs)
private HttpClient httpClient = new HttpClient();
private CancellationTokenSource cts = new CancellationTokenSource();

private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    Uri resourceAddress = new Uri("http://somewhere/gigabyte.zip");

    try
    {
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);

        // Do not buffer the response.
        HttpResponseMessage response = await httpClient.SendRequestAsync(
            request,
            HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);

        using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
        {
            int read = 0;
            byte[] responseBytes = new byte[1000];
            do
            {
                read = await responseStream.ReadAsync(responseBytes, 0, responseBytes.Length);
                break;
            } while (read != 0);
        }
    }
    catch (TaskCanceledException)
    {
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }
}


text:
Q: Как в Swiper пролистывать слайды после завершения анимации? Когда ты пролистываешь несколько раз идёт быстрый переход, а нужно чтобы можно было пролистывать только когда завершится анимация пролистывания. В слик слайдере такое видел
Вот пример - https://swiperjs.com/demos#effect-fade
Если быстро свайпить слайды накладываются друг на друга

A: Если я правильно понял, вам был нужен параметр loopPreventsSlide: true. Он как раз не дает использовать слайдер, пока не завершится смена слайда.
Проблема только в том, что этот параметр работает только в сочетании с зацикливанием (loop: true).
При включении зацикливания, loopPreventsSlide установлен в true по умолчанию.

html,
body {
  position: relative;
  height: 100%;
}

body {
  background: #eee;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 14px;
  color: #000;
  margin: 0;
  padding: 0;
}

.swiper-container {
  width: 100%;
  height: 100%;
}

.swiper-slide {
  background-position: center;
  background-size: cover;
}

.swiper-slide img {
  display: block;
  width: 100%;
}
<link href="https://unpkg.com/swiper@6.7.0/swiper-bundle.min.css" rel="stylesheet" />


text:
Q: Slow down scrolling speed of ListView I am trying to slow down the scroll speed in my ListView.
In my code, I've tried calling these two methods:
listview.setSmoothScrollbarEnabled(true);
listview.setFastScrollEnabled(false);

However, this isn't working. How can I slow down the scrolling speed of my ListView?


text:
Q: Parallel tasks in python I have a project in which there are three classes, two of them scan the network for anomalies and when the anomaly occur they feed them to a analyzing class.
class Scanner1():
    def scan(self):
       #do some scaning
       if True:
          Analyze.analyze(event)`
class Scanner2():
    def scan(self):
       #do some scaning
       if True:
          Analyze.analyze(event)
class Analyze():
    def analyze(self,event):
       #process event

I need all classes to run parellel but I am relatively new to python and I wasn't able to find any good way to make it work. I tried some threads but that didn't work. So I wanted to know if there is some to do it.

A: What you are looking forward to is multiprocessing and threading. You should consider this module https://docs.python.org/2/library/multiprocessing.html .
Also you can look at this tutorial http://www.tutorialspoint.com/python/python_multithreading.htm .


text:
Q: How can I draw/work with pixels in python with opengl/pyglet and change sizes of this pixels? I need to draw pixels and then change their sizes, so one display pixel contains 9 program pixels
import random
from pyglet.gl import *
from OpenGL.GLUT import *

win = pyglet.window.Window()

@win.event
def on_draw():
    W = 200
    H = 200
    glClearColor(0, 0, 0, 1)
    glClear(GL_COLOR_BUFFER_BIT)
    data = [[[0] * 3 for j in range(W)] for i in range(H)]
    for y in range (0, H):
      for x in range (0, W):
          data[y][x][0] = random.randint(0, 255)
          data[y][x][1] = random.randint(0, 255)
          data[y][x][2] = random.randint(0, 255)

    glDrawPixels(W, H, GL_RGB, GL_UNSIGNED_INT, data)

    glutSwapBuffers()

 pyglet.app.run()

I get this error

glDrawPixels(W, H, GL_RGB, GL_UNSIGNED_INT, data)
  ctypes.ArgumentError: argument 5: : wrong type

A: The data which are passed to glDrawPixels has to be an array of GLuint values, rather than a nested list of values.
If you want to define the color channels by integral values in the range [0, 255], then you've to use the data type GLubyte and the corresponding OpenGL enumerator constant GL_UNSIGNED_BYTE rather than GL_UNSIGNED_INT.
e.g.
data = [random.randint(0, 255) for _ in range (0, H*W*3)]
glDrawPixels(W, H, GL_RGB, GL_UNSIGNED_BYTE, (GLubyte * len(data))(*data))

If you would use GLuint respectively GL_UNSIGNED_INT anyway, then the integral color channels have to be in range [0, 2147483647]:
e.g.
data = [random.randint(0, 2147483647) for _ in range (0, H*W*3)]
glDrawPixels(W, H, GL_RGB, GL_UNSIGNED_INT, (GLuint * len(data))(*data))


text:
Q: One div per scroll in jQuery I have an idea but I do not know where to start. I want to make my site which is comprised of four rows of div to be scrollable but one division per scroll (means it must adjust to the screen size 100% in height and width) or just by clicking the arrow down/up button. Where should I start in implementing this? Is this possible? Please help make my dreams come true. Thanks. :)

A: You can give this jQuery plugin a shot: http://alvarotrigo.com/fullPage/
It has both scroll and click events and a pretty active/up-to-date GitHub repo: https://github.com/alvarotrigo/fullPage.js

A: I've made a simple example, however fullPage.js worth checking too (+1 rags02).
http://codepen.io/anon/pen/hBcrb


text:
Q: Database for Search Engine For research purposes, I have a need for a database system. I am building a search engine which uses two Inverted Index with millions of entries and an index containing simple key-value entries with the "values" containing the documents.
Everything is implemented in C++ and running on windows. It must also be open-source. So far, in dev I was loading everything in memory but since I'm now moving to bigger datasets, it's not possible.
I'm thinking of a document-oriented database. No need for big  functionalities since I will be making only simple Select and Insert however performance is an issue.
I'm open to any suggestion. Thanks

A: If you are using C++ then you can try building it over Xapian.
Xapian is a highly adaptable toolkit which allows developers to easily add advanced indexing and search facilities to their own applications. It supports the Probabilistic Information Retrieval model and also supports a rich set of boolean query operators.


text:
Q: Print SSRS Report Programatically SharePoint Integrated mode I have an application that programmatically prints a SSRS report using Reporting Services Web service.
The application works fine when I print the reports to my local test server. Reporting services is configured in native mode. I'm now trying to use this application on a different server, the report is in SharePoint and Reporting services is configured to integrated mode.
I'm struggling with my report path for the print command on my application, the report path is -
http://SERVERNAME/ReportFolder/ReportName

When I try print I get this error.
<ErrorCode xmlns="http://www.microsoft.com/sql/reportingservices">rsItemNotFound</ErrorCode>

I've tested the report URL in internet explorer and that is working correctly but when I try send this URL to the print command in the application I get the error.
Please let me know if you need any more information.


text:
Q: Is there a way to seek to a specifc line in Python? I'm teaching myself programming and today's challenge is to write a program that can align text left,right or centre. My major problem is that once I open a file, I'm not sure how to write to specific lines. Is there an easy way to do this? This is what I have. I'm thinking I will need to somehow figure the bytes in the line so that I can f.seek to the end of the line. I feel like python would already have this type of functionality somewhere but I couldn't find it searching online. Any suggestions?
def align():
    name= input('what is the name of your txt file?: ')
    try:
        f=open(name + '.txt','r+')
        lines =f.readlines()
        just = input('left, right, or centre?: ')
        for i in range[,lines]:
            j = lines[i].strip('\n')
            if just == 'right':
                f.seek() #I want it to seek each line but can't figure out what variable might go here...
                f.write('{:>30}'.format(line.strip()))
            elif just == 'left':
                f.seek() #I want it to seek each line but can't figure out what variable might go here...
                f.write('{:<30}'.format(line.strip()))
                f.seek() #I want it to seek each line but can't figure out what variable might go here...
            elif just == 'centre' or just == 'center':
                f.write('{:^30}'.format(line.strip()))
        else:
            print("You didn't choose a justification!")
        f.close()

A: There's a lot of duplication in your code, it can / should be eliminated, for example, the following handles all three possibilities:
for line in infile:
    print '{:{}{}}'.format(line.strip(), align, width)

where width is a number, and align - one of <, > or ^.
As to the "seek" problem, as others already suggested, it's better to redirect the output in another file instead of rewriting the input file "in place":
with open("in.txt", 'r') as infile, open("out.txt", 'w') as outfile:
   for line in infile:
        outfile.write('{:{}{}}\n'.format(line.strip(), align, width))

A with statement like with open(...) as var: do stuff is roughly the same as the following:
  var = open(...)
  do stuff
  close(var)

but far less error-prone.

A: No, you can't seek to a given line directly (unless all lines are exactly of the same length in which case you might be able to computer the correct offsets).
The two approaches you have is to read all of the
file into memory at once using readlines(), or do do it line-by-line and keep a count, like this:
with open('data.txt') as inf:
     for count, line in enumerate(inf, 1):
         if count == 10:
             print 'found "{}" at line 10.'.format(line)

enumerate() will keep a count for you automatically starting with 1
Note that opening the file using with will make sure the file is properly auotmatically closed when you are done with it, or an exception occurs.
The alternate approache with readlines() will read the whole file into a list and you can access a given line via the index. This may be a problem with memory if the file is huge.
Once you have the line(s) you are interested in, you can format and write it out to a different file as needed.


text:
Q: Creating circle using QGIS In QGIS I have added the shape layer to the toolbar, but I can never seem to select the shapes.
How do I create a simple circle?

A: *

*Create a new polygon layer and select it

*Enable Editing Mode

*Draw your shapes


text:
Q: Change chances of picking a random string I would like Anna to have 67% chance of being picked randomly, Bob to have a 30% change, and Tom to have a 3% chance. Is there a simpler way to do this?
This is what I have so far:
var nomes = ['Anna', 'Bob', 'Tom'];
var name = nomes[Math.ceil(Math.random() * (nomes.length - 1))];
console.log(name);

A: Based on this Stack Overflow I think the following code will work for you:

function randomChoice(p) {
  let rnd = p.reduce((a, b) => a + b) * Math.random();
  return p.findIndex(a => (rnd -= a) < 0);
}

function randomChoices(p, count) {
  return Array.from(Array(count), randomChoice.bind(null, p));
}

const nomes = ['Anna', 'Bob', 'Tom'];

const selectedIndex = randomChoices([0.67, 0.3, 0.03], nomes);
console.log(nomes[selectedIndex]);

// Some testing to ensure that everything works as expected:

const odds = [0, 0, 0];

for (let i = 0; i < 100000; i++) {

  const r = randomChoices([0.67, 0.3, 0.03], nomes);
  odds[r] = odds[r] + 1;

}

console.log(odds.map(o => o / 1000));

A: Here's a short solution for you:

function pick(){
  var rand = Math.random();
  if(rand < .67) return "Anna";
  if(rand < .97) return "Bob";
  return "Tom";
}

console.log( pick() );


text:
Q: how to replace richtextbox.rtf if and only if the whole word match? my original replace code is.
rtTextArea.Rtf = rtTextArea.Rtf.Replace(oldtext, newtext);

but the problem is it replaces all occurence of the words instead of the required word
e.g origianl word :- hello my name is serak and am in israel
replace() -- is with are the whole word chages to  "are serak and am in arereal"
is there anyway i can include a condition or something to match the whole word?
 my working environment C#.

A: Use Regular expressions. In this example the \b represents a Word Boundary.
var regExp = new System.Text.RegularExpressions.Regex(@"\bis\b");
rtTextArea.Rtf = regExp.Replace(rtTextArea.Rtf, "are");

A: The previous post showed
var regExp = new System.Text.RegularExpressions.Regex(@"\b"+oldtext+@"\b");
rtTextArea.Rtf = regExp.Replace(rtTextArea.Rtf, newtext);
Which is a little different from the first post. Notice the extra  b  and  @
This worked for me.

A: Using RegEx for this is the correct approach, but just for brevity you could also prepend/append a space to the word you want to replace to ensure it is not a part of another word.
e.g. wordToReplace = " " + wordToReplace + " ";


text:
Q: Metaphor/Analogies for Rings and Fields? What kind of analogies or "metaphors" to "real-life things" for rings and fields are there, if any? I'm studying for a final, was just wondering if there's anything concrete to help me wrap my head around these concepts. I understand the mathematical definitions, but I'm also having trouble "visualizing" them.
For example, someone used a language translation as an analogy for isomorphisms and other morphisms (like how an isomorphism is a perfect 1-1 language translation, while homomorphisms may translate from one lang. to another, but not necessarily back to the same word). Is there anything along that line for rings and fields? Thank you.


text:
Q: Interchange of limit and discontinuous function I encountered the following statement in some lecture notes and it does not seem right to me. I just wanted to have my thoughts verified or falsified.
$(X_n)_{n\in\mathbb{N}}$ is a sequence of random  variables and $X_n \to X$ almost surely for some r.v. $X$. The claim is as follows.
$$P\{X_n > b\} \to P\{X > b\}$$
for any $b \in \mathbb{R}$.
I have a counter example for this claim. Take a probability space with two elements: $\omega_1,\omega_2$. Set $P\{\omega_1\} = P\{\omega_2\} = 1/2$.
Define $X_n(\omega_1) = 1 + \frac{1}{n}$ and $X_n(\omega_2) = 0$. Then define $X(\omega_1) = 1$ and $X(\omega_2) = 0$ so that the convergence hypothesis holds.
Take $b = 1$. $P\{X_n > b\} = 1/2$ for every $n$ but $P\{X > b\} = 0$. So the assertion in the lecture notes seems to be false. The reason is as follows.
While it is correct by the dominated convergence theorem that
$$\lim_{n\to\infty}P\{X_n > b\} = E[ \lim_{n\to\infty} 1_{X_n > b}]$$
it is not true that
$$E[ \lim_{n\to\infty} 1_{X_n > b}] = E[ 1_{\underbrace{\lim_{n\to\infty} X_n}_X > b}]$$
since the indicator function is not continuous.


text:
Q: Pass data from Row into Javascript function I have a button in a webgrid row defined as such:
grid.Column("Fault", header: "Fault", format: (item) =>
            {
                if (item.Fault != null)
                {
                    return new HtmlString(string.Format("<input type='submit' id='btnShowFault' onclick='ShowFaultMessage({0})' value='Fault' />", item.Fault.Message));
                }

                return "";
            }))

This is my ShowFaultMessage function:
 function ShowFaultMessage(message) {

    $.ajax({
        url: '/Home/Message/',
        data: message,
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
            var w = window.open("/Home/Message", "Fault Message", "width=400, height=400");
            $(w.document.body).html(result.responseText);
        }
    });
};

This is not working though. I know that item.Fault is correct because my If Block works in the column definition. But when I click the button, it throws an undefined reference exception. How can I make this work. I am new to MVC, but something like this is really easy with xaml. I refuse to believe it's not possible in razor/mvc.
EDIT: This is my action method for loading the popup window view:
 public ActionResult Message(string faultMessage)
    {
        var model = new MessageViewModel { Message = faultMessage };
        return View(model);
    }

Also edited my other code blocks to show their current state.

A: Rewrite the return to be something like this
return new HtmlString(string.format("<input type='submit' id='btnShowFault' onclick='ShowFaultMessage({0})' value='Fault' />", item.Fault));

You need to use the string.format to insert the value into the string


text:
Q: How to remove django-filter additional keywords in form fileld label When i customize search type in the filter:
django_filters.CharFilter(lookup_expr='icontains')

it adds '[field_name] contains' keyword to the end of displaying label in template {{ field.label }}. I specifically use verbose_name='Some filed' argument in my model to make it accessible in template, but filter modifies it for inexplicable reason.
Is there any option for it to be displayed as i set it in versbose_name?
UPD:
Solved this adding this to settings.py
 def FILTERS_VERBOSE_LOOKUPS():
    from django_filters.conf import DEFAULTS

    verbose_lookups = DEFAULTS['VERBOSE_LOOKUPS'].copy()
    verbose_lookups.update({
        'exact': (''),
        'iexact': (''),
        'contains': (''),
        'icontains': (''),
    })
    return verbose_lookups

A: You can add the label parameter to the filter to explicitly set the field's label:
django_filters.CharFilter(lookup_expr='icontains', label='the label')

https://django-filter.readthedocs.io/en/master/ref/filters.html#label
Also, if you don't like the way django-filters creates its filters, you can play with the FILTERS_VERBOSE_LOOKUPS setting (https://django-filter.readthedocs.io/en/master/ref/settings.html#verbose-lookups-setting). I haven't tested it but it says that you can set it to False to disable this behavior - you may want to try this instead.


text:
Q: Unable to access new OFBiz 16.11 plugin I am trying to learn OFBiz 16.11, but I am facing an error when adding a new plugin and tying to access it using its url.
:ERROR MESSAGE:
org.apache.ofbiz.widget.renderer.ScreenRenderException: Error rendering screen [component://common/widget/CommonScreens.xml#login]: org.apache.ofbiz.widget.renderer.ScreenRenderException: Error rendering screen [component://ofbizDemo/widget/CommonScreens.xml#main-decorator]: java.lang.IllegalArgumentException: Could not find resource bundle [OfbizDemoUiLabels] in the locale [en_US] (Could not find resource bundle [OfbizDemoUiLabels] in the locale [en_US]) (Error rendering screen [component://ofbizDemo/widget/CommonScreens.xml#main-decorator]: java.lang.IllegalArgumentException: Could not find resource bundle [OfbizDemoUiLabels] in the locale [en_US] (Could not find resource bundle [OfbizDemoUiLabels] in the locale [en_US]))

I ran the following commands to create a new plugin:
--Initialize OFBiz and load demo data
gradlew cleanAll loadDefault ofbiz

--Add new plugin
gradlew createPlugin -PpluginId=ofbizDemo

--Apply changes and run OFBiz
gradlew loadDefault ofbiz

I am currently testing OFBiz using Windows 10.
New plugin URL: https://localhost:8443/ofbizDemo
Is there any missing step during the creation of the new plugin which is causing this error message?
Note that the above commands can be found in OFBiz tutorial document:
Tutorial Document
I checked the OfbizDemoUiLabels.xml file and it exists in its correct location.

A: I found the solution. Simply removed all non-English entries in the OfbizDemoUiLabels.xml file. It is now working as expected!

A: It is happening because the current language has been set to English (United States) [en-US]. Just change the language to "English- [en]" from the top right "language" menu, at left of "logout" and "visual themes".

Alternatively, edit the config file:
apache-ofbiz-16.11.xx\specialpurpose\ofbizDemo\config\OfbizDemoUiLabels.xml
Replace all-
<value xml:lang="en">OfbizDemo Application</value>

With
<value xml:lang="en-US">OfbizDemo Application</value>

A: I just faced the same problem. I solved it by adding entries for my system's default language (which is german) to the OfbizDemoUiLabels.xml,
e.g. <value xml:lang="de">OfbizDemo Applikation</value>


text:
Q: Asymptotic behaviour of real sequences Let's say we have two real sequences $(a_n)_{n\in\mathbb{N}}$ and $(c_n)_{n\in\mathbb{N}}$ with $c_n\in o(\frac1n)$ (i.e. $c_n(\frac1n)^{-1}\xrightarrow{n\rightarrow\infty}0$). And for all $\epsilon>0$ holds that
$$\frac{1-\epsilon}n-\frac1\epsilon |c_n|\leq a_n\leq \frac{1+\epsilon}n+\frac1\epsilon |c_n|.$$Is it true that $a_n\sim \frac1n$ i.e. $a_n(\frac1n)^{-1}\xrightarrow{n\rightarrow\infty}1$? I think it should hold but I'm really confused by the $\epsilon$'s because I can't just consider the limit for $\epsilon\rightarrow0$.
Thanks and I'm sorry if it's a really stupid question!

A: Fix $\epsilon\gt0$. Then $n|c_n|\to0$ and, for every $n$,
$$
1-\epsilon-\epsilon^{-1}n|c_n|\leqslant na_n\leqslant1+\epsilon+\epsilon^{-1}n|c_n|,
$$
hence
$$
1-\epsilon\leqslant\liminf_{n\to\infty}\,na_n\leqslant\limsup_{n\to\infty}\,na_n\leqslant1+\epsilon.
$$
This holds for every $\epsilon\gt0$ hence
$$
1=\liminf_{n\to\infty}\,na_n\leqslant\limsup_{n\to\infty}\,na_n=1,
$$
which implies
$$
\liminf_{n\to\infty}\,na_n=\limsup_{n\to\infty}\,na_n=1,
$$
that is
$$
\lim_{n\to\infty}na_n=1.
$$


text:
Q: Running XNA On Lower-End Graphics Card I am looking to work with the XNA framework to develop some simple 2D games. I especially would like to be able to develop and debug portions of these games while on-the-go with my netbook. Unfortunately, my netbook's GPU does not support the Shader Model 2.0 that is required by XNA.
Frustrated, I went to Google looking for alternatives. I came across one alternative from "Riemers XNA Tutorial". The following code is supposed to force XNA to run strictly through a computer's CPU, thus allowing my netbook to run an incredibly slow version of XNA.
if (GraphicsAdapter.DefaultAdapter.GetCapabilities(DeviceType.Hardware).MaxPixelShaderProfile < ShaderProfile.PS_2_0)
            graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs> (SetToReference);
     }

     void SetToReference(object sender, PreparingDeviceSettingsEventArgs eventargs)
     {
         eventargs.GraphicsDeviceInformation.CreationOptions = CreateOptions.SoftwareVertexProcessing;
         eventargs.GraphicsDeviceInformation.DeviceType = DeviceType.Reference;
         eventargs.GraphicsDeviceInformation.PresentationParameters.MultiSampleType = MultiSampleType.None;
     }

The above code is supposed to be placed in the Game1 method of a default XNA project.
The problem is that when I try to run this new project I receive the following two errors:
Error   1   'XNAReferenceDevice.Game1.LoadGraphicsContent(bool)': no suitable method found to override  c:\users\richard\documents\visual studio 2010\Projects\WindowsGame1\WindowsGame1\WindowsGame1\Game1.cs  39  33  WindowsGame1

Error   2   'XNAReferenceDevice.Game1.UnloadGraphicsContent(bool)': no suitable method found to override    c:\users\richard\documents\visual studio 2010\Projects\WindowsGame1\WindowsGame1\WindowsGame1\Game1.cs  46  33  WindowsGame1

These two errors also cause blue 'squiggly' lines to appear beneath the LoadGraphicsContent and UnloadGraphicsContent methods.
If anyone could help me solve this problem or point me in a different direction, that would be great.
Thanks in advance!

A: New versions of XNA lost some compatibility with the past.
Probably you are using a newer version of the framework and of XNA than Riemers tutorials.
However, consider that new XNA 4.0 supports minimum pixel shader 2.0! It means you cannot run it on low end machines with only pixel shader 1.1 or with a too slow pixel shader 2.0.
Previous version, XNA 3.1, supports minimum pixel shader 1.1, you can try to switch back to that using visual studio 2008 express.
Sorry but since XNA requires good machines I think you should find a better machine, also for doing 2D graphics.
The compiler error however is not related to pixel shader but is related probably to XNA and C# versions.


text:
Q: How do I unset a value in a multi-dimensional array? I'm trying to unset a value from a multi-dimensional array when an user presses a button. The array looks like this:
array(1) {
  [1726]=>
  array(2) {
    [1736]=>
    int(1)
    [1737]=>
    int(4)
  }
  [2314] =>
  array(2) {
    [1436]=>
    int(3)
    [1567]=>
    int(4)
    [2457]=>
    int(7)
    }
}

I'm trying to unset for example
$_SESSION['cart'][1][1]

What Ï've tried so far:
switch ($action) {
    case 'add':
        $_SESSION['cart'][$deb_id][$product_id]++;
        var_dump($_SESSION['cart']); exit();
        break;
    case "remove":
        $_SESSION['cart'][$deb_id][$product_id]--;
        if($_SESSION['cart'][$deb_id][$product_id] == 0) unset($_SESSION['cart'][$deb_id][$product_id]);
    break;
    case 'delete':
        unset($_SESSION['cart'][$deb_id][$product_id]);
    break;
}

A: how about
 $_SESSION['cart'][$deb_id][$product_id] = '';
 unset($_SESSION['cart'][$deb_id][$product_id]);


text:
Q: Extarct SQL tables information Schema I need to extract all the information in the tables given database. I have only one option to get all the information Schema are as;
SELECT *
FROM INFORMATION.SCHEMA
WHERE TABLE_NAME = '<table_name>'

but this is taking a lot more time consuming by extracting one by one, I need to get all the tables information schemas for one CSV file.


text:
Q: Show that $\sum_{m,n = - \infty}^{\infty} \frac{(-1)^m}{m^2 + 58 n^2} = - \frac{\pi \ln( 27 + 5 \sqrt {29})}{\sqrt {58}} $ I wonder why this is true
$$ \sum_{m,n = - \infty}^{\infty} \frac{(-1)^m}{m^2 + 58 n^2} = - \frac{\pi \ln( 27 + 5 \sqrt {29})}{\sqrt {58}} $$
Where the sum omits the case $n = m = 0$ ofcourse.

A: Finally I managed to sum this series using Ramanujan's class invariants. We have the definition $$g(q) = 2^{-1/4}q^{-1/24}\prod_{n = 1}^{\infty}(1 - q^{2n - 1}), \, g_{p} = g(e^{-\pi\sqrt{p}})\tag{1}$$ Ramanujan established that if $p$ is a positive rational number then $g_{p}$ is an algebraic real number. Moreover we have the non-trivial identity $$g_{4/p} = 1/g_{p}\tag{2}$$ Another ingredient we need is the formula $$\sin \pi z = \pi z\prod_{n = 1}^{\infty}\left(1 - \frac{z^{2}}{n^{2}}\right)\tag{3}$$ Taking logs and differentiating with respect to $z$ we get $$\pi\cot\pi z = \frac{1}{z} -2z \sum_{n = 1}^{\infty}\frac{1}{n^{2} - z^{2}}$$ Replacing $z$ by $iz$ we get $$\pi\coth\pi z = \frac{1}{z} + 2z\sum_{n = 1}^{\infty}\frac{1}{n^{2} + z^{2}}$$ The above sum can be written as $$\sum_{n = 1}^{\infty}\frac{1}{n^{2} + z^{2}} = \frac{\pi}{2z} - \frac{1}{2z^{2}} + \frac{\pi e^{-2\pi z}}{z(1 - e^{-2\pi z})}\tag{4}$$ Consider the sum in question
\begin{align}
S(p) &= \sum_{m, n\in\mathbb{Z}}'\frac{(-1)^{m}}{m^{2} + pn^{2}}\notag\\
&= 2\sum_{m = 1}^{\infty}\frac{(-1)^{m}}{m^{2}} + 2\sum_{n = 1}^{\infty}\sum_{m\in\mathbb{Z}}\frac{(-1)^{m}}{m^{2} + pn^{2}}\notag\\
&= 2\sum_{m = 1}^{\infty}\frac{(-1)^{m}}{m^{2}} + \frac{2}{p}\sum_{n = 1}^{\infty}\frac{1}{n^{2}}+ 4\sum_{n = 1}^{\infty}\sum_{m = 1}^{\infty}\frac{(-1)^{m}}{m^{2} + pn^{2}}\notag\\
&=\frac{(2- p)\pi^{2}}{6p} + 4\sum_{n = 1}^{\infty}\sum_{m = 1}^{\infty}\frac{(-1)^{m}}{m^{2} + pn^{2}}\notag\\
&=\frac{(2- p)\pi^{2}}{6p} + 4\sum_{m = 1}^{\infty}(-1)^{m}\sum_{n = 1}^{\infty}\frac{1}{m^{2} + pn^{2}}\notag\\
&= \frac{(2- p)\pi^{2}}{6p} + \frac{4}{p}\sum_{m = 1}^{\infty}(-1)^{m}\sum_{n = 1}^{\infty}\frac{1}{m^{2}(1/p) + n^{2}}\notag\\
&= \frac{(2- p)\pi^{2}}{6p} + \frac{4}{p}\sum_{m = 1}^{\infty}(-1)^{m}\left(\frac{\pi\sqrt{p}}{2m} - \frac{p}{2m^{2}} + \frac{\pi\sqrt{p} e^{-2\pi m/\sqrt{p}}}{m(1 - e^{-2\pi m/\sqrt{p}})}\right)\text{ (using equation }(4)) \notag\\
&=\frac{\pi^{2}}{3p}-\frac{2\pi\log 2}{\sqrt{p}}+\frac{4\pi}{\sqrt{p}}\sum_{m=1}^{\infty} \frac{(-1)^{m}q^{m}}{m(1-q^{m})},\,q=e^{-2\pi/\sqrt{p}}\notag\\
&=\frac{\pi^{2}}{3p}-\frac{\pi\log 4}{\sqrt{p}}+\frac{4\pi}{\sqrt{p}}(a(q^{2})-a(q))\notag\\
&\, \, \, \, \,\,\,\,\text{where }a(q) =\sum_{n=1}^{\infty} \frac{q^{n}} {n(1-q^{n})}=-\log\prod_{n=1}^{\infty}(1-q^{n})\notag\\
&=\frac{\pi^{2}}{3p}-\frac{\pi\log 4} {\sqrt{p}}+\frac{4\pi}{\sqrt{p}}\log\prod_{n=1}^{\infty}(1-q^{2n-1}) \notag\\
&=\frac{\pi^{2}}{3p}-\frac{\pi}{\sqrt {p}} \log\frac{2}{q^{1/6}g^{4}(q)}\text{ (via equation }(1)) \notag\\
&= -\frac{\pi\log(2/g_{4/p}^{4})}{\sqrt{p}}\notag\\
&= -\frac{\pi\log (2g_{p}^{4})}{\sqrt{p}}\text{ (using equation }(2))\notag
\end{align}
It is well known that $g_{58} = \sqrt{(5 + \sqrt{29})/2}$ and this gives the desired closed form for $S(58)$. The above technique can also be used (with some more effort) to prove the Kronecker's second limit formula.

The function $a(q) $ used above is related to work of Simon Plouffe. See this answer for details.

A: *

*Let $F=\mathbb{Q}(\sqrt{-58}),\mathcal{O}_F=\mathbb{Z}[\sqrt{-58}]$.
Its ideal class group is $C_F= \{ (1),(2,\sqrt{-58})\}$
thus the ideals with their norm are $N((n+\sqrt{-58}m))= n^2+58m^2$, $  N(\frac{2n+\sqrt{-58}m}{2}(2,\sqrt{-58}))= \frac12(4n^2+58m^2)$

then your series is $\ \ 2 \ L(1,\psi)$

where $\psi((n+\sqrt{-58}m))=1, \psi(\frac{2n+\sqrt{-58}m}{2}(2,\sqrt{-58}))=-1$ is the Hecke character induced by the non-trivial character of $C_F$.
$$  L(s,\psi) = \sum_I \psi(I) N^{-s} =\frac{1}{|\mathcal{O}_F^\times|} \sum_{n,m \in \mathbb{Z}^2}' N((n+\sqrt{-58}m))^{-s}- 2^{s}  N((2n+\sqrt{-58}m))^{-s}$$

*Using $|C_F| = 2$ and some class field theory, we find that $H = F(\sqrt{-2})$ is the Hilbert class field of $F$ and $$\zeta_H(s) = \zeta_F(s) L(s,\psi)$$
Now by chance it happens that $H/\mathbb{Q}$ is itself an abelian extension. Thus we can write $\zeta_H$ as a product of Dirichlet L-functions
$$\zeta_H(s) = \zeta(s)\ L(s,{\scriptstyle \left(\frac{-58}{.}\right)})\ L(s,{\scriptstyle \left(\frac{-2}{.}\right)})\ L(s,{\scriptstyle \left(\frac{29}{.}\right)})$$
Together with $\displaystyle\zeta_F(s) = \zeta(s)\ L(s,{\scriptstyle \left(\frac{-58}{.}\right)})$ it means $$L(1,\psi) = L(1,{\scriptstyle \left(\frac{-2}{.}\right)})\ L(1,{\scriptstyle \left(\frac{29}{.}\right)})$$
and we use quadratic reciprocity to write $(\frac{-d}{.}) = (\frac{.}{\Delta})$ and conclude.

A: (Too long for a comment.)
We have,
$$ \sum_{m,n = - \infty}^{\infty} \frac{(-1)^m}{m^2 + 10n^2} = - \frac{2\pi \ln( \sqrt2\; U_{5})}{\sqrt {10}} $$
$$ \sum_{m,n = - \infty}^{\infty} \frac{(-1)^m}{m^2 + 58 n^2} = - \frac{2\pi \ln( \sqrt2\; U_{29})}{\sqrt {58}} $$
with fundamental units $U_5 = \frac{1+\sqrt5}2$ and $U_{29} = \frac{5+\sqrt{29}}2$.
P.S. Presumably there might be a family for $d = 5,\,13,\,37$.

Added:
Courtesy of a comment by Paramanand Singh, we have the closed-form in terms of the Dedekind eta function $\eta(\tau)$ as,
$$\sum_{m,n = - \infty}^{\infty} \frac{(-1)^m}{m^2 + pn^2} = - \frac{2\pi \ln(\sqrt2\,g_p^2)}{\sqrt {p}} =- \frac{\pi \ln(2\,g_p^4)}{\sqrt {p}} $$
where,

$$g_p = 2^{-1/4}\frac{\eta(\tfrac12\sqrt{-p})}{\eta(\sqrt{-p})}$$

In particular,
$$\sum_{m,n = - \infty}^{\infty} \frac{(-1)^m}{m^2 + 6n^2} = - \frac{2\pi \ln\big(\sqrt2\,(1+\sqrt2)^{1/3}\big)}{\sqrt{6}}$$
$$\sum_{m,n = - \infty}^{\infty} \frac{(-1)^m}{m^2 + 22n^2} = - \frac{2\pi \ln\big(\sqrt2\,(1+\sqrt2)\big)}{\sqrt{22}}$$
and more complicated ones for $d=5,\,13,\,37$.


text:
Q: Should nouns after "any" be singular or plural? While I was answering a question on ELL, I got confused with a comment from a fellow user. After I indicated that:

"Do you have any idea to prove it?'

is grammatically correct, the OP commented that "ideas" should be used in place of "idea".
The comment befuddled me. I thought until now that "any" should be followed by singular noun and not plural. So I searched Google and saw it's a huge debate going on and there is no end to it. I got no perfect and trustworthy source. So I thought to post the question here.
So what is the right rule? Should singular or plural be used after "any"?

A: The correct use changes depending on the sentence:

Do you have any idea how to do this?
  Do you have any idea what to do?
  Do you have any ideas for me?
  Do you have any ideas for how to do this?

It seems that, if the singular or plural noun (idea) is directly connected by a subordinating conjuction (how / what / where / which / that), you use the singular; if it's modified by a prepositional phrase (for...) or by nothing at all, you use the plural.
Without using all that grammar jargon, I'd say use the singular if it's followed by how, what, that, who, whom, whose, which, etc, and use the plural otherwise.

A: The NOAD (New Oxford American Dictionary) has a note about using any:

When used as a pronoun, any can be used with either a singular or a plural verb, depending on the context: "we needed more sugar but there wasn't any left" (singular verb) or "are any of the new videos available?" (plural verb).

In "English Grammar" (David Daniels & Barbara Daniels, ISBN 0-06-467109-7), any is listed between the pronouns that can be either plural or singular, among all, more, and some.
Looking for do you have any idea for on the Corpus of the Contemporary American English, I get a single sentence.

But what happened was that the network came to us—because we have a little production company that does my specials—and said, do you have any idea for a show?

Looking for do you have any ideas for, I get three sentences:

Do you have any ideas for the next movie?

Well, then," said Avette, "do you have any ideas for another topic?"

Do you have any ideas for me?

Looking for "do you have any idea(s) to," I get the following sentences:

Do you have any idea to this day how you stacked up against the men?

So, do you have any ideas to help cows and sheep stop with the gas problem?

Do you have any ideas to boost union membership?

The Corpus of Contemporary American English doesn't have any example of the phrases I searched for the period 2010-2012. The sentences containing any ideas to/for are dated 2005-2009 (the most recent ones), while the sentences containing any idea to/for are dated 1995-1999.

A: Conjugating "to do" demonstrates that "does" is used with a (third person) singular object. Now, since "Do any here object?" sounds right, but "Does any here object?" doesn't suggests that "any" regards a plurality. Also, the fact that the word "anyONE" exists at all suggests that "any" refers to a plurality.

A: If you have learnt a rule that "any" can only be connected with a singular noun, it is wrong. "Any" can be used with singular or plural according to sense.

Is there any question?

The speaker indicates that there is probably no more than one question.

Are there any questions.

The speaker indicates that there might be several questions.
See OALD

A: To me, the word 'any' should always be followed by a singular noun.
Example: Do you have any idea as to when this work will get done?
Having said that, the below is also correct.
Example: Do you know any of these boys, who fled the scene on the other day?"


text:
Q: displaying downloaded images in my phone gallery I'm trying to tell my app to make some images which are already downloaded appear in the gallery of my phone.
the images are well download and displayed in my app, they have no extension, their names are only a md5.
here is how i'm trying to do so:
public static void makePhotoAppearOnGallery(Activity activity, String md5) {
        final String extStorageDirectory = Environment
                .getExternalStorageDirectory().toString();
        final String festivalDirectory_path = extStorageDirectory
                + Constants.IMAGES_STORAGE_PATH;
        File imageOutputFile = new File(festivalDirectory_path, "/");
        if (imageOutputFile.exists() == false) {
            imageOutputFile.mkdirs();
        }
        File imageFile = new File(imageOutputFile, md5);
        Bitmap bm = decodeFile(imageFile.getAbsoluteFile());
        OutputStream outStream = null;
        try {
            outStream = new FileOutputStream(imageFile);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        try {

            outStream.flush();
            outStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        scanFile(imageFile,activity);

    }
     public static void scanFile(File downloadedFile, Context mContext){
         Uri contentUri = Uri.fromFile(downloadedFile);
         Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
         mediaScanIntent.setData(contentUri);
         mContext.sendBroadcast(mediaScanIntent);
     }

the app crashes on this line:
MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");

with this message:

java.io.FileNotFoundException: /mnt/sdcard/data/com.example.app/images: open failed: EISDIR (Is a directory)

Does anyone know from what it comes?

A: I had the same problem. It turns out this error happens when there is a folder with the same file name. For example I had a folder named "log.txt".


text:
Q: Room compile problem - column references a foreign key but it is not part of an index I'm new to android app development and am creating an app that has Trips which stores Locations.
I'm getting a compile error :"trip_Id column references a foreign key but it is not part of an index. This may trigger full table scans whenever parent table is modified so you are highly advised to create an index that covers this column."
I have 2 tables: Trip & Location.
I've tried indexing the tripId and the locationId in their respective classes but it doesn't solve the issue.
A Trip has its id (PK), title, description and priority.
A Location has its locationId (PK), tripId(FK), locationName and LatLng of the place.
@Entity(tableName = "location_table",
        foreignKeys = @ForeignKey(entity = Trip.class, parentColumns = "location_Id", childColumns = "trip_Id"),
        indices = {@Index(value = {"locationId"}, unique = true)})
public class Location {

    @PrimaryKey(autoGenerate = true)
    private int locationId;

    @ColumnInfo (name = "trip_Id")
    private int tripId;

    private String locationName;

    @TypeConverters(LatLngConverter.class)
    private LatLng latLng;

@Entity(tableName = "trip_table", indices = {@Index(value = {"id"}, unique = true)})

public class Trip {

    @PrimaryKey(autoGenerate = true) // with each new row SQLite will automatically increment this ID so it will be unique
    @ColumnInfo (name = "location_Id")
    private int id;

    private String title;

    private String description;

    private int priority;

I can't seem to find out what's wrong

A: That message is a warning, there would be other errors (see 2nd suggested line). e.g.

Using indices = {@Index(value = {"locationId"}, unique = true),@Index(value = {"trip_Id"})}) should overcome that warning.
HOWEVER, there is no need to have an (additional) index on locationId as it is already indexed being the primary key (this would be a waste and also inefficient). So it is suggested that you use :-
indices = {@Index(value = {"trip_Id"})})

I believe that your overall issue is that you are referring to the object's variable name for the column, when if you have @ColumnInfo(name ="????") then you should be referring to the given name

*

*i.e. ???? is the column name in the underlying table.

You should also be using location_Id instead of id in the Trip:-
@Entity(tableName = "trip_table", indices = {@Index(value = {"location_Id"}, unique = true)})

A: I had this problem when I had quite a few foreign keys. I found out (after a lot of trial and error) that I set up my indices wrong... whoops. :P
Wrong:
indices = [
    Index("active_color_style_id",
        "ambient_color_style_id",
        "hour_hand_dimensions_id",
        "minute_hand_dimensions_id",
        "second_hand_dimensions_id")
]

Right:
indices = [
    Index("active_color_style_id"),
    Index("ambient_color_style_id"),
    Index("hour_hand_dimensions_id"),
    Index("minute_hand_dimensions_id"),
    Index("second_hand_dimensions_id")
]

Full example:
@Entity(
    tableName = "analog_watch_face_table",
    foreignKeys = [
        ForeignKey(
            entity = WatchFaceColorStyleEntity::class,
            parentColumns = ["id"],
            childColumns = ["active_color_style_id"],
            onDelete = NO_ACTION
        ),
        ForeignKey(
            entity = WatchFaceColorStyleEntity::class,
            parentColumns = ["id"],
            childColumns = ["ambient_color_style_id"],
            onDelete = NO_ACTION
        ),
        ForeignKey(
            entity = WatchFaceArmDimensionsEntity::class,
            parentColumns = ["id"],
            childColumns = ["hour_hand_dimensions_id"],
            onDelete = NO_ACTION
        ),
        ForeignKey(
            entity = WatchFaceArmDimensionsEntity::class,
            parentColumns = ["id"],
            childColumns = ["minute_hand_dimensions_id"],
            onDelete = NO_ACTION
        ),
        ForeignKey(
            entity = WatchFaceArmDimensionsEntity::class,
            parentColumns = ["id"],
            childColumns = ["second_hand_dimensions_id"],
            onDelete = NO_ACTION
        )
    ],
    indices = [
        Index("active_color_style_id"),
        Index("ambient_color_style_id"),
        Index("hour_hand_dimensions_id"),
        Index("minute_hand_dimensions_id"),
        Index("second_hand_dimensions_id")
    ]
)


text:
Q: Problem: Need to refresh pages for Polyfill.io to work The polyfills are working great at making my website works wit IE, but not on the first load. I need to refresh every pages every time to get Polyfill.io to works in IE 11. All you're supposed to need to get it to work is this script tag:
<script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?features=es2015"></script>

Pretty hard to recreate my problem with the snippet tool, so if you don't mind using my website to recreate it, it would be very appreciated.
Link to my website
Otherwise here's a video of what is happening.
Video showing Polyfill.io needing a refresh on each page
I am unfortunately not very familiar with this, but I feel so close to goal and also want my website to works in IE. What am I doing wrong?

A: I found that you set IE=8 in meta tag in your website. If I set document mode to 11 in F12 dev tools, the website can run well in IE 11:

So you could try to change IE=8 into IE=Edge in meta tag, which means using <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> and test again.


text:
Q: ERROR CanUpgrade [SPConfigurationDatabase] failed The following errors are showing up in the logs a couple times per day:
ERROR CanUpgrade [SPConfigurationDatabase] failed
SharePoint Foundation Upgrade SPUpgradeSession ERROR Exception: Login failed for user 'domain\machinename$'

I have checked the patch status, servers in farm, and have run the SP Config wizard, and I can't find any component claiming to need an upgrade. Is there any way to track down what is causing this error to be thrown, or why it's using this account to access the config database?
This issue was blogged about here, with a recommendation to add the account as a shell admin, but granting permissions to a local machine account doesn't seem like a best practice. Any thoughts?

A: 1.This error is not related to the PSConfig execution.

*I agree that the granting the machine name is not best practice in terms of security.

*I had a ticket open for that case with MS and their advice was to grant the access to machine to only config DB (no access to content db). from that point on don't have those issues.
Unfortunately I cannot share the internal communication details with MS Premier Support.
I ran other farm without that setting and apart from noise in ULS I don't see any negative effect on that farm.


text:
Q: Why is this integral equal to $1$? (VBIL) Let $p(y \mid \theta)$ be a likelihood and $\hat{p}_N(y \mid \theta)$ be an unbiased estimator of it.
In VBIL they define $z = \log \hat{p}_N(y \mid \theta) - \log p(y\mid \theta)$ and call its density $g_N(z \mid \theta)$. Then they say the following expectation is equal to $1$
$$
\int e^z g_N(z \mid \theta) dz = 1
$$
Why is this the case? Of course I tried the following
$$
\frac{1}{p(y \mid \theta)} \int p(y \mid \theta) e^z g_N(z \mid \theta) dz = \frac{1}{p(y \mid \theta)}\int \hat{p}_N(y \mid \theta) g_N(z \mid \theta) dz
$$
but this doesn't lead anywhere as we are integrating with respect to $z$ so we can't use the unbiasedness property.


text:
Q: Linear programming: How to introduce a second decision variable (array) in SCIPY optimization? In  scipy.optimize.linprog(c, A_eq, b_eq) , the resulting solution is a decision variable (array) called  x  that multiplies with array  c .
How to admit a second decision variable (array) called  y in the constraint vector  b_eq  and have linprog minimize the main objective function so that the  y  is also optimized for, not just  x ?
In other words, instead of minimizing the objective function by finding the optimal xarray only, we want to minimize the objective function by finding the optimal  x  array as well as the newly introduced  y  array.
This same question was made a few months ago, but no answers were useful:
Same question link


text:
Q: filter date wise, month wise and year wise data in dygraph
i have added my code below, in this i wanted to add date, month, year wise data filter is it possible in this dygraph.,i don't know how to do.

    <marquee>Online Graph</marquee>

in this it reads full data from csv and displays all, but i want to restrict it, by user click the button the graph will show like last 100 records, date wise, monthwise and year wise .,pls guide me


text:
Q: Error when trying to run Java related commands on MacOS For example, if I do java -version I get:
Error: dl failure on line 542
Error: failed /Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home/lib/server/libjvm.dylib, because dlopen(/Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home/lib/server/libjvm.dylib, 10): no suitable image found.  Did find:
    /Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home/lib/server/libjvm.dylib: code signature invalid for '/Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home/lib/server/libjvm.dylib'

What am I to do? I have JDK installed:
Matching Java Virtual Machines (1):
    14, x86_64: "Java SE 14"    /Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home

and I've intalled JRE as well though I get the error if I try to invoke java.
My Mac Details:
OS X Yosemite
Version 10.10.5 (14F27)
Processor 2.66 GHz Intel Core 2 Duo

MacBook Pro (15-inch, Mid 2009)

A: That is a fairly old version of OS X with a brand spanking new version of the JDK, which might not have been built in a way intended to be run on that old of a version of OS X.  I'd recommend trying out AdoptOpenJDK 8 or 11, and see if things work better there.


text:
Q: IP Multicast - would this work on my dual homed embedded Linux device? I am working on an embedded Linux project.  It has a cell modem that comes up as ppp0 and a single Ethernet interface eth0 that may or may not be connected.  The cable could be unplugged at any time from eth0 or may never be plugged in.
Is it possible to setup multicasting so that it could intelligently send the outgoing traffic over eth0 if it's up, otherwise over ppp0?  If so I would be very interested on how to do this.
Thanks,
Fred


text:
Q: Speeding up loop in python I running into some  performance problems and I would appreciate a quick look at this.
I'm reading frequency domain data and I need to make a data cube for compensating the start frequencies in time domain.
The way I do this now is:
compdata = [[np.exp(t_range*sflist[y]) for y in x] for x in sfcube]

where
t_range = 1j*2*np.pi*time_axis_ns
time_axis_ns = np.array([x*delta_time_ns for x in xrange(number_of_points_for_fft)])
sflist = array([ 29500000.,  30500000.])

sfcube is a NxM array with indexes for sflist.
Calculating compdata is by far the slowest part of my program now, any ideas for optimization?

A: Quick win would be to parallelize it across all your CPU cores (+HT if available) using multiprocessing module.
from multiprocessing import Pool
pool = Pool(16)  ## use total number of cores, x2 if HT is supported.

def f(y):
    return np.exp(t_range*sflist[y])

compdata = [pool.map(f, x) for x in sfcube]

Of course this will get you 4-fold to 16-fold speed improvement (depending on number of cores). Still, if that's not good enough, you need to figure out how to do that with vector/matrix operations.

A: Here's your calculation and an alternative, more numpythonic take on it:
compdata = [[np.exp(t_range*sflist[y]) for y in x] for x in sfcube]
compdata2 = np.take(np.exp(sflist[:, None] * t_range), sfcube, axis=0)

With this sample data set based on your question:
sfcube = np.random.randint(2, size=(100, 100))
delta_time_ns = 100
number_of_points_for_fft = 1024
time_axis_ns = np.array([x*delta_time_ns for x in xrange(number_of_points_for_fft)])
t_range = 1j*2*np.pi*time_axis_ns
sflist = np.array([ 29500000.,  30500000.])

I get these timings:
In [3]: %timeit compdata = [[np.exp(t_range*sflist[y]) for y in x] for x in sfcube]
1 loops, best of 3: 1.76 s per loop

In [4]: %timeit compdata2 = np.take(np.exp(sflist[:, None] * t_range), sfcube, axis=0)
10 loops, best of 3: 72.2 ms per loop

That's a 20x speed-up, although your result will change, depending on the actual sizes of sflist and sfcube. And what you get is a 3D numpy array, not a list of lists of arrays, although they are interchangeable in most settings, and of course:
In [5]: np.allclose(compdata, compdata2)
Out[5]: True

A: You can use Python-psyco library
http://psyco.sourceforge.net/
http://en.wikipedia.org/wiki/Psyco
or any other similar library
It may speed up your program.

A: If you have an array of indices, you can use it to vectorize the calculation:
In [1]: a = numpy.random.random((4,4))

In [2]: a
Out[2]:
array([[ 0.08746418,  0.57716752,  0.85863208,  0.42931856],
       [ 0.90259153,  0.19590983,  0.73075288,  0.88976529],
       [ 0.71843135,  0.0169308 ,  0.98336314,  0.22227009],
       [ 0.93776916,  0.58943769,  0.55040806,  0.92192396]])

In [3]: a[0]
Out[3]: array([ 0.08746418,  0.57716752,  0.85863208,  0.42931856])

In [7]: index=[(0,1), (0,1)]

In [8]: a[index]
Out[8]: array([ 0.08746418,  0.19590983])

In [9]: a[index] = 100*a[index]

In [10]: a[index]
Out[10]: array([  8.74641837,  19.59098276])

This is usually much faster than using Python lists. Note that a is a NumPy array from the start, and the the indices I use are in the form a[list_of_rows, list_of_columns]

A: Firstly, you can create your time_axis_ns array using:
time_axis_ns = np.arange(number_of_points_for_fft)*delta_time_ns

Then rather than you iterating over indices in sfcube:
sflist[sfcube]

Should give the same result. Then do your np.exp(t_range* on the result of this.


text:
Q: Oracle connection manager Java Client example I am new to Oracle connection manager. Can some help me with a Java Client code example to talk to a oracle database through Oracle connection manager.

A: Quote from oracle docs.
The Web server on which the Connection Manager is running is on host webHost and is listening on port 1610. The database to which you want to connect is running on host oraHost, listening on port 1521, and SID ORCL. You write the URL in TNS keyword-value format:
String myURL =
   "jdbc:oracle:thin:@(description=(address_list=
   (address=(protocol=tcp)(port=1610)(host=webHost))
   (address=(protocol=tcp)(port=1521)(host=oraHost)))
   (connect_data=(INSTANCE_NAME=orcl))
   (source_route=yes))";
   OracleDataSource ods = new OracleDataSource();
   ods.setURL(myURL);
   ods.setUser("scott");
   ods.setPassword("tiger");
   Connection conn = ods.getConnection();

The first element in the address_list entry represents the connection to the Connection Manager. The second element represents the database to which you want to connect. The order in which you list the addresses is important.
When your applet uses a URL such as the one above, it will behave exactly as if it were connected directly to the database on the host oraHost.


text:
Q: Is it possible defines rules about groups in Plone? When I go in "Zope Management Interface" > "Security" I can set permissions for users.
Can I do the same for groups?
There is a method or a plugin for this goal?

A: No you can't (set permissions for users); that tab sets permissions for roles; see Permissions and roles in the "Understanding permissions" manual.
You can assign roles to individual users and groups.

A: It is not advisable to map permissions to roles via the "Security" tab in the ZMI.  You should instead create workflows (ZMI-->portal_workflow) and customize permissions through it.
In your workflow, you need to define states and transitions.  And within each state, you can manage what permissions to give to specific roles.  If you need to, you can also map groups to roles.
After customizing your workflow, you then assign it to specific content types (in portal_workflow).
Don't forget to run "update security" so that your new workflow will be applied to existing content.


text:
Q: The conversion of nvarchar value "0854697543" overflowed an int column in select command I have a select command, and it returns answer records, but it also gives an error in  Visual Studio 2010's query builder with this query:
SELECT  *
FROM    Orders
WHERE   (BCode = 025) AND (Date BETWEEN '1390%' AND '1391%') OR
        (Date BETWEEN '1390%' AND '1391%') AND (MCode = 0123456789)

The error is:

Error Message: the conversion of nvarchar value "0854697543"
  overflowed an int column

Data types are
BCode : nvarchar(50)
Date :  nvarchar(50)
MCode : nvarchar(10)

Where is the problem?

A: Shouldn't it be
AND (MCode = '0123456789')

?
Otherwise it will try to use 0123456789 as an integer which will lead to the conversion error.
In addition, you're repeating yourself in the logic (Date BETWEEN...), more concise:
WHERE   (Date BETWEEN '1390%' AND '1391%') AND
        ((BCode = 025) OR (MCode = '0123456789'))

A: I think I understand where the problem is: you're comparing MCode (which is a nvarchar) with an integer value (0123456789) in your query, so engine is trying to convert your field to int for every record!!
Try this
SELECT  *
FROM    Orders
WHERE   (BCode = '025') AND
        (LEFT(Date, 4) = '1390' OR LEFT(Date, 4) = '1391') AND
        (MCode = '0123456789')

As I've already told you in my comment: don't use nvarchar(50) to store dates!! Use appropriate data type (DateTime or Date for example) for every column: it will avoid headaches in future, makes query design easier and makes query execution really faster!


text:
Q: How to get the Value of an Object by using Value of Array as Key I have an array which holds multiple values.
I also have an object which contains data.
Now I want to create an object which only holds the the data which has the same key as the value of the array.
const array = ["foo", "bar", "foo2", "bar2"]
var obj = {foo:"string1", fue:"string2", bar:"string3"

The Object I want to create should look like this:
var result = {foo:"string1", bar:"string3"}

A: Just iterate over the object keys and see if they exist in array using Array.prototype.includes and add the values in a result object

const array = ["foo", "bar", "foo2", "bar2"]
var obj = {foo:"string1", fue:"string2", bar:"string3"}
var result = {};
Object.keys(obj).forEach(key => {
   if(array.includes(key)) {
        result[key] = obj[key];
   }
})

console.log(result)

Also as @Jacob pointed out, it would be more efficient if you loop over the array and pick keys from the object  if they exist as accesing keys from object is O(1) operation whereas checking in array is an O(n) operation

const array = ["foo", "bar", "foo2", "bar2"]
var obj = {foo:"string1", fue:"string2", bar:"string3"}
var result = {};
array.forEach(key => {
   if(obj[key]) {
        result[key] = obj[key];
   }
})

console.log(result)

A: This would be my approach:
const obj = { foo:"string1", fue:"string2", bar:"string3" };

const subset = pick(obj, ["foo", "bar", "foo2", "bar2"]);

function pick(obj, props) {
  return props.reduce((result, prop) => {
    return (prop in obj) ? Object.assign(result, { [prop]: obj[prop] }) : result;
  }, {});
}

(If you are already using lodash, there's a _.pick method that does this).


text:
Q: Stripe - How to get purchaser's information for a charge with Connect (Express)? I've set up a test charge using stripe.Charge.create() and it is working, i.e. I can see the dollar amounts processed in the Connect test dashboard. It appears to be money going from the tok_visa to a dummy Stripe account I set up.
charge = stripe.Charge.create(
  amount=1000,
  currency="usd",
  source="tok_visa",
  application_fee_amount=123,
  transfer_data={
    "destination": "{{CONNECTED_STRIPE_ACCOUNT_ID}}",
  }
)

For a marketplace type platform, I need to be able to send funds from the purchasing user to the selling user, however.
Would I need to get the purchaser's account (or some other object?) to use as the "source" in the charge?
How do I get that to put it into the "source" field?
I feel a little lost in Stripe's docs, so I could be missing something. Thank you for any tips.

A:
I need to be able to send funds from the purchasing user to the
  selling user, however

If by 'purchasing user' you mean a cardholder customer of your marketplace, this is exactly what you have. tok_visa here represents a credit card, that you accept through a payment page.
If instead you mean, the purchasing user is another connected account in the marketplace, you can either :

*

*use an account debit to debit one account, and then transfer to
another.

*collect a card from users when they sign up and create a
Customer object for them. You can then charge that customer as needed
like in your example code. You need to maintain a link in your system that
'customer cus_xxx is also my marketplace user acct_xxx'


text:
Q: Styling Angular Component's Element from Main SCSS I'm struggling with something in my Angular 5.x app, and hope someone can help...
I've got a component that has a mat-raised-button, and currently I've got some styling for it within the component's SCSS file:
button-themed {
background-color: black;
color: white;
border-color: red;
border-style: solid;
border-width: 1px;}

Everything looks fine that way. However, I now want to shift that styling up to some theme SCSS files I'm working on. How can I get the styling to apply when it's in my "red-theme.scss" or "blue-theme.scss" files?
(I'm looking to be able to dynamically swap between themes and want the button to adjust according to the theme)
UPDATE
I kicked the tires some more on custom theming, and am getting nowhere. What am I missing? Below is some quick test stuff I tossed together (I'm simply trying to get the button's border to change color so I can see that the process works).
settings.component.scss:
.test-button {
    border-style: solid;
    border-width: 1px;
}

settings.theme.scss:
@mixin test-theme($theme) {
  $primary: map-get($theme, primary);
  $warn: map-get($theme, warn);
  .test-button {
    background-color: mat-color($primary);
    color: mat-color($warn);
    border-color: mat-color($warn);
  }
}

settings.component.html:
<button mat-raised-button class="test-button">TEST</button>

red-theme.scss:
$test-primary: mat-palette($mat-pink, 800, 300, 900);
$test-accent: mat-palette($mat-pink);
$test-warn: mat-palette($mat-indigo, 600);
$test-theme: mat-light-theme($test-primary, $test-accent, $test-warn);

styles.scss:
@import '~@angular/material/theming';
@import 'themes/color-palettes.scss';
@include mat-core();
@import 'app/pages/settings/settings.theme.scss';
@mixin custom-components-theme($theme) {
  @include test-theme($theme);
}
@import 'themes/red-theme.scss';
.red-theme {
  @include angular-material-theme($test-theme);
}

It compiles and my button displays, but there's no color change to the button's border (even though other Material components have changed color on the page). Can anyone help nudge me in the right direction?

A: One of those "argh!" moments, but I thought I'd post this as an answer in case anyone stumbles upon this post... The custom component mixin is the way I'm going at this point in time. I'm hopeful I can figure out all the other items I'll have to custom theme.
The reason my first test (shown in my original post) didn't work is because I forgot to add the line to actually import my custom component theme within styles.scss:
.red-theme {
  @include angular-material-theme($test-theme);
  @include custom-components-theme($test-theme);
}

A: How about something like this in your components?
:host-context(.theme-light) p {
   background-color: white;
}
:host-context(.theme-dark) p {
   background-color: black;
}


text:
Q: Replace Existing XMLTooling Library w/ Compiled Version To remediate an Shibboleth SSO vulnerability (https://shibboleth.net/community/advisories/secadv_20180227.txt) I'm attempting to replace the existing libxmltooling7 library with a newer version (from 1.6.0-4 to 1.6.3).
I've successfully downloaded source, built dependencies, complied and verified the new library is installed in /usr/local...though dkpg -l is still showing the old version:
#
Output of dkpg -l | grep xmlt...
pi libxmltooling7:amd64 1.6.0-4switchaai1~trusty1 amd64 C++ XML parsing library with encryption support (runtime)
#
Am I missing a symbolic link somewhere?

A: Try this before installing new one :
 dpkg -r --force-depends libxmltooling7


text:
Q: How to check if entry is number including float numbers Is there a simple way or function to check if the entry to the Editbox is numeric including float numbers. Any alphabetic or alphanumeric entries will not be allowed. Without float number part I would check ascii but I think it does not work for float numbers.
Thanks

A: Since your question is tagged with mfc, here is a code snippet using CString:

CString ss;
float ff;
GetDlgItemText(IDC_MY_EDIT_BOX, ss);
if (_stscanf_s(ss, _T("%f"), &ff) == 1)
    // ff contains the value
else
    // error

If you need to use a double precision number, use "%lf" in the scanf call.

EDIT:
CString ss;
float ff;
GetDlgItemText(IDC_MY_EDIT_BOX, ss);
LPCTSTR lpszString = ss;
TCHAR *endptr;
ff = (float) _tcstod(lpszString, &endptr);
if (endptr != lpszString && *endptr == '\0')
    // ff contains the value
else
    // error

A: If it is a dialog you can add an edit control to the Dialog. Than Launch the Dialog wizard add a variable to this edit control. Choose type float. The DDX_Text Routine will do the rest.
But this will permit entry of alphabetic chars. If you want to fix this too. You can subclass the edit control with a Special OnChar (WM_CHAR) handler that only allows decimal numbers and the decimal point.


text:
Q: Changing Option Menu after pressing Back button when using Fragments and back stack? I am using one single activity where I replace a fragment with another when the user select an menu item from the options menu.
I have implemented the back stack using addToBackStack() and onBackPressed().
Everything works fine, except that when a user pressed the Back button, the fragment is replaced but the Options menu is showing the previous item.
How can I make it so that the Options Menu changes back to the previous item when the user pressed the Back button?


text:
Q: How to structure "user friends" collections in MongoDB? I have a questions about what is the best way to structure "user connections" system in MongoDB, like Linkedin works.
I have the next options but I don't know what is the best way in the future, with millions rows in collections.

*

*Option 1: Two collections, user and user-connect relation
one-to-one in user-connect with this fields: user_one, user_two,
status ("pending", "accepted", "rejected", "bloecked"). When user
request connect to another user, I need just insert a new document in
user-connect collection, but I have a problem: I need to follow all
queries to get "contacts" of a user in two fields, user_one and
user_two because just exists one insert between both.

*Option 2: The same structure that option 1 but instead of 1 insert, 2
inserts: The first one will be the request, just a document with
status pending, and the second one will be when this connection is
accepted. Two documents, two insert but when I need to query for user
contacts, just need to get information in one field: user_one

*Option 3: one-to-many structure, user-connect will has an user_one
field and contacts field, array of user ids, but reading another
forums, this not is recommended because a lot of "match" system in the
future.


text:
Q: Detect links in messages in Discord.js I'm new to discord.js. I'm trying to check if a message contains a link like "Hi, I'm from discord.gg/xxxxx and now I'll spam my link".
How can I check if the message contain the link?

A: I am unsure if you want to check for discord invite links specifically, or if you want to check for all links. Either way, you can use message.content.includes.
Example:

bot.on('message', (message) => { //whenever a message is sent
  if (message.content.includes('discord.gg/'||'discordapp.com/invite/')) { //if it contains an invite link
    message.delete() //delete the message
      .then(message.channel.send('Link Deleted:\n**Invite links are not permitted on this server**'))
  }
})

A: You can try this:
bot.on(`message`, async message => {
    const bannedWords = [`discord.gg`, `.gg/`, `.gg /`, `. gg /`, `. gg/`, `discord .gg /`, `discord.gg /`, `discord .gg/`, `discord .gg`, `discord . gg`, `discord. gg`, `discord gg`, `discordgg`, `discord gg /`]
    try {
        if (bannedWords.some(word => message.content.toLowerCase().includes(word))) {
            if (message.author.id === message.guild.ownerID) return;
            await message.delete();
            await message.channel.send(`You cannot send invites to other Discord servers`);
        }
    } catch (e) {
        console.log(e);
    }
});

(There was a missing ")")

A: I find this is the best:
let regx = /^((?:https?:)?\/\/)?((?:www|m)\.)? ((?:discord\.gg|discordapp\.com))/g
let cdu = regx.test(message.content.toLowerCase().replace(/\s+/g, ''))

Tell me if it works!

A: What you are doing works but you don't need .then() just leave the message.channel.send() as it is.

A: You can check this using Regular Expressions (RegEX)
Example:
// The message to check for a Discord link
var message = "Hi, please join discord.gg/a2dsc for cool conversations";

// The message will be tested on "discord.gg/{any character or digit}"
var containsDiscordUrl = message.test(/discord.gg\/\w*\d*);

// If the test has found a URL..
if (containsDiscordUrl) { // ... Do something }

A: let regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;

I think this is helping you.


text:
Q: Importing Github Library and Only Work With Library To make it clear, I'm aware on how to import a library from github to my eclipse workspace and that isn't the  problem.
I'm trying to import https://github.com/MartinvanZ/Inscription. If one were to look at the library, you'd see that the actual library isn't in the root but in a seperate folder.
Example:
Git Library
    library(folder)
    sample(folder)
    random files (licence, readme, etc)

I just want to import the library folder as a android project and then modify it and when I push it to the repo, it just gets pushed to the library folder.
How do I do this? If not possible, what can I do similar to what I want?

A: I believe the problem here is that the library in question does not contain the files required to be imported directly as an Eclipse project. Specifically, it is missing .project and .classpath files. To get this project into Eclipse, you'll have to create a new project. Select File -> New -> Android Project and the pick the option that says "Create project from existing source."
This should create the required .project and .classpath files, without harming the .git directory.


text:
Q: Azure VMSS with Application gateway Usecase:
I need to launch VM with VMSS inside application gateway depending on CPU utilization .
In VMSS I need to execute once script if anyone has done this before please share the doc for same.
Thanks.
I have created a custom template but during deployment giving error:
{
  "status": "Failed",
  "error": {
    "code": "ResourceDeploymentFailure",
    "message": "The resource operation completed with terminal provisioning state 'Failed'.",
    "details": [
      {
        "code": "VMExtensionProvisioningError",
        "message": "VM has reported a failure when processing extension 'updatescriptextension'. Error message: \"Enable failed: failed to execute command: command terminated with exit status=1\"."
      }
Template: https://github.com/linuxgambler/azure/blob/master/vmss.json

A: You could create a single Azure Resource Manager template that creates an App Gateway, scale set, and autoscale rules. I'm not aware of a single example, but there are examples of App Gateway VMSS templates here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vmss-ubuntu-app-gateway and here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vmss-windows-app-gateway
An example using autoscale rules for CPU usage is here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vmss-ubuntu-autoscale and here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vmss-windows-autoscale - you could take the autoscale rules from the latter examples and add them to an app gateway template.
If you create such a template you can script its deployment with PowerShell or CLI. If you are looking to imperatively create resources and add autoscale rules using PowerShell or CLI commands, you can do this too, though again I'm not aware of a one-stop example script, but you can build a script from other examples. For example, instructions for adding autoscale rules to a scale set using PowerShell can be found here: https://msftstack.wordpress.com/2017/03/05/how-to-add-autoscale-to-an-azure-vm-scale-set/

A: That error message you're seeing is due to the custom script extension for linux you are running; in your configuration you have:

"settings": {
  "commandToExecute": "sh /test.sh",
  "enableInternalDNSCheck": "false"
}

But there's no fileUris key to specify where the test.sh file is to be downloaded from (example of how to do this here: https://github.com/Azure/azure-quickstart-templates/blob/master/201-vmss-bottle-autoscale/azuredeploy.json#L229). So it could be that the test.sh file isn't on the VM (unless you got it there some other way?); it could also be something else; you could check the logs in /var/lib/waagent to see what how far the extension got; if you see files in /var/lib/waagent/custom-script/downloads/0, then you should be able to see the stdout and stderr logged there as well.


text:
Q: Mock not overriding the return of a function in Python I am implementing unit test on one of the classes of my project. The method that I want to test is queryCfsNoteVariations:
class PdfRaportDaoImpl:
        def queryCfsNoteVariations(self, reportId):
        sql = """
select v.* from item_value_table v
where v.table_id in
(select table_id from table_table t
    where t.report_id=%s and table_name='CFS')
"""
        cfsItemList = dbFind(sql, (reportId))

        sql = "select * from variations_cfs_note"
        cfsNoteVariations = dbFind(sql)
        if cfsNoteVariations == None or len(cfsNoteVariations) == 0:
            raise Exception("cfs note variations is null!")

        cfsNoteVariationList = []
        for itemInfo in cfsItemList:
            for cfsNoteVariation in cfsNoteVariations:
                if (
                        cfsNoteVariation["item_name_cfs"].lower()
                        == itemInfo["item_name"].lower()
                ):
                    cfsNoteVariationList.append(cfsNoteVariation["item_name_cfs_note"])
            if len(cfsNoteVariationList) > 0:
                return cfsNoteVariationList, itemInfo["item_note"]
        return None, None

Which has a path: /com/pdfgather/PDFReportDao.py
In my test I am doing patch on dbFind() method which is located in /com/pdfgather/GlobalHelper.py. My current test looks like this:
from com.pdfgather.PDFReportDao import PdfReportDaoImpl

@patch("com.pdfgather.GlobalHelper.dbFind")
    def test_query_cfs_note_variations(self, mock_find):
        mock_find.side_effect = iter([
[{"item_name" : "foo"}, {"item_name" : "hey"}],
        [{"item_name_cfs": "foo"},
         {"item_name_cfs": "foo"},
         {"item_name_cfs": "hey"}]]
])
        report_id = 3578
        result = TestingDao.dao.queryCfsNoteVariations(report_id)

        # Printing result
        print(result)

However I am not getting my desired result which is getting inside a loop and returning from inside a loop. Instead the dbFind is returning nothing (but it shouldn't as I already preassigned returning values for dbFind).
Thanks in advance!

A: Python refers com.pdfgather.PDFReportDao.dbFind and com.pdfgather.GlobalHelper.dbFind as two different classes. The second one is the import you want to patch. Try changing your patch to:
@patch("com.pdfgather.PDFReportDao.dbFind")


text:
Q: Django strange behaviour of aggregation over custom ManyToMany field I've encountered some unexpected (for me) behavior of aggregation over ManyToMany field in django.
I have the following schema:
class ContestTaskRelationship(models.Model):
    contest = models.ForeignKey('Contest', on_delete=models.CASCADE)
    task = models.ForeignKey('Task', on_delete=models.CASCADE)
    solved = models.ManyToManyField('User', related_name='contests_tasks_solved', blank=True)
    cost = models.IntegerField(default=0)

class Contest(models.Model):
    tasks = models.ManyToManyField('Task',
                                   related_name='contests',
                                   blank=True,
                                   through='ContestTaskRelationship')

class Task(models.Model):
    pass

Then I have one task and two contests, connected to that task. If I try to annotate count of ContestTaskRelationship models like that (assuming contest is one of the contests):
task = contest.tasks.annotate(number_solved=Count('contesttaskrelationship')).first()

I get task.number_solved == 1, but when I try like that:
task = Task.objects.filter(id=1).annotate(number_solved=Count('contesttaskrelationship')).first()

I get the expected result task.number_solved == 2. Why is that? Isn't it the same object and the same field?
UPD: I found out that in the first example additional condition is added to query, the contest_id is compared to the id of corresponding contest. Is it documented somewhere? I couldn't find anything.

A: When you write this code:
Task.objects.get(id=1)

you will get the Task instance, and it seems that there is method named 'annotate'  with 'number_solved' argument in your Task model. You cannot do any annotate after some queryset methods: get, count, aggregate, last, first, exists and may be some more. This methods do not return queryset.
If you want to see the query, and compare it.
You can do two things:

*

*print(Contest.objects.all().query)  # return raw query to db

*install django-extensions and use this command to add shell:
~# python manage.py shell_plus --print-sql

if you see the query you can compare it and solve this problem by yourself


text:
Q: Send different emails for last row / and additional rows I need to modify an existing macro by which I can perform the following functions:

*

*Should have the option to enter the number of rows required to draft the email/s.

*The Macro should include the last row plus the number of rows entered

(eg. I enter "5" that would mean Last row + 4 rows above it).

*Individual email should be drafted for each row.

(eg. Last row would be Mailto = Colleague3@hotmail.com ; MailSubject = "EmailSubject_As_Per_the_Cell" Mailbody = "Hi Friend3, I'm inviting you for the conference being held today."

*Other details are should be retained as is. (eg. Signatures etc.)

NOTE: My Excel sheet has 6-7 Columns which contains all the Project no./meeting no./Presenter Name/ Atendees name etc.
I tried tweaking with the VBA code but I'm not able to get through it.
Sub Mail_Outlook()
    Dim OutApp As Object
    Dim OutMail As Object, signature As String
    Dim irow As Integer

    Dim objItem As Object
    irow = InputBox("How many Invites do you want to send?")

    LastRow = ActiveSheet.Range("E" & Rows.Count).End(xlUp).Row

    If Cells(LastRow, 1).Value <> "" Then
        Mailto = Cells(LastRow, 1).Offset(0, 5).Value
        If Mailto = "Colleague1" Then Mailto = "Colleague1@hotmail.com"
        If Mailto = " Colleague2" Then Mailto = " Colleague2@hotmail.com"
        If Mailto = " Colleague3" Then Mailto = " Colleague3@hotmail.com"
    End If

    MailSubject = Cells(LastRow + irow, 1).Offset(0, 4).Value & " – Important Message"

    MailBody = "Hi " & Cells(LastRow, 1).Offset(0, 5).Value & "," & vbNewLine & vbNewLine & _
    " I'm inviting you for the conference being held today." & _
    vbNewLine

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

    With OutMail
         .Display
    End With

    signature = OutMail.body
    With OutMail
        .Subject = MailSubject
        .To = Mailto
        .body = MailBody & vbNewLine & signature
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub

A: I'm presupposing you have the Outlook stuff handled correctly...  this looks like it's not actually sending any emails, just creating emails that are ready to be sent?
See if these changes bring you any closer to what you seek.  This code is lightly tested but are by no means bulletproof.
Sub Mail_Outlook()
    Dim OutApp As Object
    Dim OutMail As Object, signature As String
    Dim irow, i As Integer

    Dim objItem As Object
    irow = InputBox("How many Invites do you want to send?")

    Set OutApp = CreateObject("Outlook.Application")

    LastRow = ActiveSheet.Range("E" & Rows.Count).End(xlUp).Row

    For i = 0 To irow - 1

      Set OutMail = OutApp.CreateItem(o)

      If Cells(LastRow - i, 1).Value <> "" Then
          Mailto = Cells(LastRow - i, 5).Value
          If Mailto = "Colleague1" Or _
               Mailto = " Colleague2" Or _
               Mailto = " Colleague3" Then
             Mailto = Mailto & "@hotmail.com"
          End If
      End If

      MailSubject = Cells(LastRow - i, 4).Value & " – Important Message"
      MailBody = "Hi " & Cells(LastRow - i, 5).Value & "," & vbNewLine & vbNewLine & _
        " I'm inviting you for the conference being held today." & _
        vbNewLine

      With OutMail
        .Display
        signature = .body
        .Subject = MailSubject
        .To = Mailto
        .body = MailBody & vbNewLine & signature
      End With

    Next i

    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub


text:
Q: what is the Aws cloudwatch events equivalent in gcp How we can Monitor Resource Changes In Google Cloud and how to monitor for GCP resource changes, automate alerts based on those changes and invoke an action.

A: There is a complete Operation Suite(formerly known as Stackdriver) on Google Cloud Platform that provides the features mentioned above.
Official documentation: https://cloud.google.com/products/operations
Cloud Monitoring, Cloud Alerting can be used to alerts based on different events. Alerts can be published to different channels like email, slack, etc.


text:
Q: Encountered a problem with strcat and strcpy in c++ visual studio So I was trying to use strcat and strcpy function in c++ in visual studio, and I have encountered an error and the compiler told me to use strcat_s and strcpy_s. When I used those functions, the errors were nullified and it gave me my output.
But when I defined a function ex and used strcat_s inside the ex function, it gave me an error, telling me `'strcat_s': function does not take 2 arguments
#include <iostream>
#include <string.h>
using namespace std;

void ex(char a[], char b[]) {
    cout << strcat_s(a, b);
}
int main() {
    string str;
    char a[20], b[20];
    cin >> a >> b;
    ex(a, b);
    cout << a <<" "<< b;
    cin >> str;
    cout << str;
    return 0;
}

Can someone please explain what's the problem here?

A: The declaration says that strcat_s is an overloaded function with either 2 or 3 arguments:
template <size_t size>
errno_t strcat_s(
   char (&strDestination)[size],
   const char *strSource
);

errno_t strcat_s(
   char *strDestination,
   size_t numberOfElements,
   const char *strSource
);

In you original program you used the first version, while in context of ex() the argument a[] is decayed to a pointer so it will try to use the 3 argument version.