Q:

Webscraping - Adding a If Statement if a "Nontype" object has no attribute

Thanks for reading!  For my project what I am doing is scrolling through company annual reports to pull names of board members and positions.  Because different companies have different formats I would like to try a method to scrape information, and if that process results in a "Nontype" error (because one method does not find attributes or a keyword), to move to a different method and try that method.  I just need a way to say if there is a nontype error, try the next method.  Below is one method that results in an error.
tables_ticker = annual_report_page_soup.find(text="Age").find_parent("table")
resticker = []
for row in tables_ticker.find_all("tr")[1:]:
    #print([cell.get_text(strip=True) for cell in row.find_all("td")])
    if row:
        resticker.append([cell.get_text(strip=True) for cell in row.find_all("td")])
        non_empty_ticker = [sublist for sublist in resticker if any(sublist)]
        df_ticker = pd.DataFrame.from_records(non_empty_ticker)
        df_ticker[df_ticker == ''] = np.nan
        df_ticker=df_ticker.dropna(axis=1, how='all')

print(df_ticker)

Error:
Traceback (most recent call last):
  File "C:/Users/james/PycharmProjects/untitled2/Edgar/WMT Working.py", line 84, in
    tables_ticker = annual_report_page_soup.find(text="Age").find_parent("table")
AttributeError: 'NoneType' object has no attribute 'find_parent'

A:

Here's a simple example you can apply to your code:
for item in ["Hello", "World", None, "Foo", None, "Bar"]:
    print(item.upper())

Output:
HELLO
WORLD
Traceback (most recent call last):
AttributeError: 'NoneType' object has no attribute 'upper'
>>>

As you can see, once the for-loop reaches the third item in the list (which is not a string, it's a NoneType object), an exception is raised because NoneType objects don't have an upper method. This worked for the first two iterations because strings do have an upper method.
Solution - use a try-except block:
for item in ["Hello", "World", None, "Foo", None, "Bar"]:
    try:
        print(item.upper())
    except AttributeError:
        continue

Output:
HELLO
WORLD
FOO
BAR
>>>

We encapsulated the line of code which can throw a potential AttributeError with a try-except block. If the line of code raises such an exception, we use the continue keyword to skip this iteration of the loop and move on to the next item in the list.
In the same way, you can encapsulate this line:
tables_ticker = annual_report_page_soup.find(text="Age").find_parent("table")
With a try-except block. Instead of using continue inside a loop, however, you can switch scraping formats.


Q:

cin keyword not working in text editor

I'm using the scite text editor (I cannot make use of any IDE or compiler since I'm required to also utilize Makefiles which is only possible if I use some sort of text editor) for all of my coding in c++. However, I'm consistently facing the same challenge; the text editor (I've attempted this on multiple ones including codepad and sublime text) isn't reading any input from the keyboard. Here is the source code:
#include <iostream>
#include <iomanip>
using namespace std;

const int SIZE_OF_ARRAY = 5;

int main(){
int x, y;
int counter = 0;
int elements[SIZE_OF_ARRAY];
cout << "Please enter a number ";
cin >> x;
cin.ignore();
cout << "Please enter a choice ";
cin >> y;
if(y == 1){
 for(int i = 0; i < SIZE_OF_ARRAY; i++)
  elements[i] = -1*SIZE_OF_ARRAY + x;

 for(int j = 0; j < SIZE_OF_ARRAY; j++)
  cout << elements[j] << " ";
}

 else if(y == 2){
  for(int i = 0; i < SIZE_OF_ARRAY; i++){
   if(i == 0)
    elements[i] = -1*x;
   else{
    elements[i] = elements[i-1] + 1;
   }
}

for(int j = 0; j < SIZE_OF_ARRAY; j++)
 cout << elements[j] << " ";
}

else if(y == 3){
 for(int i = 0; i < SIZE_OF_ARRAY; i++){
  counter++;
  elements[i] = 7*x*counter;
 }

for(int j = 0; j < SIZE_OF_ARRAY; j++)
 cout << elements[j] << " ";
}
}

The program is supposed to take as an input any number from the user and, depending on a numeric choice (between one and three) entered by the user, manipulate the value first entered somehow.
Choice one (User picks first choice)
The program negates the size of the array and adds the number which the user first entered and fills the array with the resulting value.
Choice Two (User picks second choice)
The program negates the number entered by the user, places this in the first array location then each successive element is added one unit more than the previous one.
Choice Three (User picks third choice)
Fills the array with the first five multiples of seven. Then shifts each number by a factor equivalent to the number the user had first entered.
I've ran it on an IDE (Codeblocks) and it works perfectly well. However, on any text editor, the 'cout' statements are printed with the variables x and y taken to each be equal to zero rather than being set to the value entered from the keyboard. It doesn't even allow any keyboard input. Any answer regarding how I can fix this would be immensely appreciated.

A:

Hoosain, continuing from the comments above, when you use an IDE, you must configure the path to your compiler as well as all compiler options you wish to use, and the location for the resulting executable and object files, etc. When you used CodeBlocks on windows, you essentially got lucky that CodeBlocks will automatically detect whether MinGW is installed and set its compiler configuration to allow you to build and run your code without you having to configure the compiler details. Geany is another editor that does a good job auto-detecting and using MinGW.
For the remaining IDE's it is up to you to configure them to find and use the compiler you have installed (MinGW), as well as configuring all desired compiler options (at minimum enable compiler warning with -Wall -Wextra).
That is where new programmers who have only used an IDE configured for them run into problems... Before you can tell an IDE where your compiler is located and which compiler options you want to use, you have to know where you compiler is located and understand what minimum set of compiler options you should use.
The way you learn to use a compiler is with the good old command line. (yep, that's cmd.exe on windows, often labeled as the "DOS Prompt" in earlier versions) An IDE is just a front-end to your compiler that executes the same commands you can simply enter on the command line to compile your program.
Learning how to use your compiler will save you an incredible amount of time when learning to code. You can simply open a command prompt and compile any file you wish, without setting up a project, etc.. When learning to code, trying to shoehorn small examples into an IDE is much more time consuming and often more trouble than it is worth. Rather than worry how to use an IDE, focus on "how to use your compiler" first.
Since you have MinGW installed on windows, all you have to do to be able to compile from the command prompt is add the path to the MinGW bin directory to your User Environment. You do that by adding the PATH as an Environment Variable here:
Start Menu-> (rt-click on Computer)-> Properties->
Advanced System Settings-> (Advanced tab)-> Environment Variables

In the Top window (your user variables), click to add (or edit) the PATH "Variable name". Generally, if you installed MinGW in the default location, you simply add the path as the "Variable value":
c:\MinGW\bin;c:\MinGW\mingw32\bin

(verify the path on your computer)
(note: windows separates path components by the semi-colon, so if there is already a PATH variable set, just add a semi-colon between what is there and what you add. Also if you already have a command prompt open, you must close it and open it again for the new path to take effect) Just open Start Menu-> Accessories-> Command Prompt (you can rt-click on the icon (top-left) and choose Properties to set the font (recommend Lucida Console 12) and height/width)
Now you have configured your command prompt to allow you to compile any file at any location within your filesystem. For example, I tested with the code you posted (I modified it to add prompts for the information). Compiling it is a piece of cake. I keep my executables in a bin directory to keep sources and binaries separate.
I named your file array_get.cpp.
Compile
Then just enter the normal g++ compiler command, and at minimum use -Wall -Wextra options to enable compiler warnings (you can add -pedantic and whatever additional warnings you want, I would recommend at least adding -Wshadow so your compiler will warn on any variables you declare in multiple scopes that could conflict). The -o option allows you to specify the location of the executable (I just use a separate bin directory as explained above). So to compile and link your code into bin\array_get.exe all I have to enter is:
C:\Users\david\Documents>g++ -Wall -Wextra -o bin\array_get array_get.cpp

(do not accept code until it compiles without warning -- read any warning (it gives line of problem), understand what it is telling you, and go fix it)
Example Use/Output
C:\Users\david\Documents>bin\array_get.exe
Please enter a number: 21
Please enter a choice (1-3): 3
147 294 441 588 735

That's it. Since MinGW uses gcc, the compiler commands you use on windows are the exact same you would use in Linux, so learning to compile from the command line pays double-benefit.
Now you have the luxury of using any text-editor to edit your code while you have the command prompt simply and easily re-compile as you wish until your code is correct. No project dialogs, no mess of a different folder for every file, just the freedom to compile any file you wish -- right from the command line. (I actually separate my sources in directory by type, e.g. c, cpp), you find what works best for your. I also use a simple bat file that takes the exename and source.cpp names as arguments and then compiles with the options I set -- it just cuts down on typing :)
Further, since you now where your compiler is located, and which options to use, you can open the Settings window on any IDE and set the appropriate compiler command and compiler options to allow the IDE compile your code for you.  Give it a try, and let me know if you have further questions.


Q:

IntegrityError when try to insert image to text

I'm just trying to insert picture in django-cms wysiwyg editor, but:
IntegrityError at /admin/cms/page/3/edit-plugin/3/edit-plugin/15/
(1452, 'Cannot add or update a child row: a foreign key constraint fails (`my-table`.`cmsplugin_filerimage`, CONSTRAINT `cmsplugin_ptr_id_refs_id_c078c386` FOREIGN KEY (`cmsplugin_ptr_id`) REFERENCES `cms_cmsplugin` (`id`))')

The same thing happens when I try to use django-cms own picture plugin.

A:

As I can see there is no way to mark comment as an answer so I'll just thank Victor for his comment. In my case the type of cmsplugin_filer tables was InnoDB while other tables' engine was MyISAM. So I just changed type of engine for filer's tables to MyISAM:
ALTER TABLE <tablename> ENGINE=MyISAM


Q:

Can I import a custom Google Map into iOS MapKit?

Let's say I have a custom fictional map create with Google maps. It is not a real place, but a custom one. Kind of like a map of the lord of the rings location, mordor or something. Working as a Google map on browser, with pins, custom image and all. Is there a way to import this to iOS MapKit to show in my own iOS app?

A:

You could try to export the google map in KML format and then use a library to parse the KML data and view it in a MKMapView.
This seems to be useful: http://kmlframework.com


Q:

PHP exec expect script with SCP then SSH

I have a PHP page which runs the following expect script to upload a file to another server on my network:
#!/usr/bin/expect -f

set password [lindex $argv 0]

spawn /usr/bin/scp /home/Dave/bin/test root@192.168.1.1:/etc/test

expect {
    -re ".*yes.*no.*" {
        exp_send "yes\r"
        exp_continue
    }
    -re ".*password.*" {
        exp_send "$password\r"
    }
}

expect eof

Before I do this however I need to backup the existing file on the server:
cp /etc/test /etc/test.bak

And after I upload the file I need to restart the service that reads the file:
/etc/init.d/testservice restart

It seems rather silly to SSH to the server three separate times. How can I do this all at once? Is there a PHP function that will take care of some or all of this for me?
Edit: Prompting the user for a password is a requirement.

A:

You can do this by running a single SSH command, but arranging the proper mix of data transfer, command execution and control logic is hard to manage.
It's easier to establish an SSH connection, do your work with whatever mixture of ssh, scp, sftp, rsync, sshfs, … suits you, and finally close the SSH connection.
SSH offers a connection that other SSH processes can piggyback on: a master connection. Start a master connection and keep it running:
ssh -N -M

Pass the credentials as input with expect, since you need to provide a password. Then run other SSH commands as you please. When you no longer need the connection, run ssh -O exit.
To ensure that the SSH commands will be slaves to the existing master connection (and hence require no authentication), pass the same ControlPath option to all SSH invocations. Either pass it as a command line option (-o ControlPath=…, note lowercase) or define it in ~/.ssh/config. The value is a path where ssh will create or look for the socket that allows the slaves and the master to communicate; it needs to be in a writable directory on a filesystem that supports named sockets, and the name needs to be unique for each connection (so it should include the target host, port and user).
See also Using an already established SSH channel and SSH easily copy file to local system


Q:

How do you report "startup experience" on your resume?

Say you've spent a significant amount of time (5 years) serially starting up companies, with enough success to keep going for 5 years, but not enough to retire rich.
And now, with a mortgage and a serious relationship, burned out, you're trying to dust off your resume and get a regular, 9-5 job.
How would you record/report on your work experience at the startups?
Making a list of technologies sounds silly (it'll get out of hand on account of size), and very incomplete (with very small, early stage startups, there is a lot more work to go around than just hacking away at code). A regular programming job also seems like a waste (with all of the mix of experience that comes from working at a startup, giving up on the additional skills learned along the way doesn't feel quite right) so reporting on the experience as one would on a regular programmers' resume might not be the correct thing.

A:

Things to Downplay
Firstly, a major concern for a lot of employers would be the "serially starting up"? Because one thing that worries employers is a lot of job changes in a short period of time. (For the obvious reason that they're worried about you jumping ship to a new job at an inconvenient point)
The other would be "burned out". Nothing says "hire someone else" like "I've done my best work, now I'd like to settle for you". You need to find a more positive way to describe what you're looking for in a company.
What to Emphasise
At the end of the day, CV's fall into two types. One is the one you put online for recruitment firms. In this case, just dump literally EVERYTHING on it. Every programming language you'd be willing to work in, every soft skill you possess, every place you've worked for. They're basically using a big ol' regex, and you want to catch as many jobs as possible so you get a good range of available jobs.
The other CV is the one you write for the companies you're actually seeking out yourself. These are the ones you tailor, for example emphasising that you've got very strong programming skills in the area the company you want to work for works with, and why you want to work for them.
Note that occasionally, a recruiting firm will contact you based on the former CV, and it's often worth drafting a CV of the latter type, in order to get past the far more stringent hiring department of the companies they send your CV on to.
The other thing that helps with either kind of CV is examples of how you've applied your soft skills.
For example: "Very Customer Focused" vs. "Customer Focus: During one project dealt with the client on a weekly basis, clarifying requirements and demonstrating prototypes over the entire project lifespan. This helped to build trust and contributed to being offered further work from this client."
The first will be picked up by the regex, along with every other CV on the internet. The second will prove that you actually did something they can talk to you about in interview, and will be picked up by the regex.
Basically, write something that hits the requirements so that it's listed when they look for it (programming languages, soft skills), but when you read it back makes you think, "I'd like to talk to this guy and find out if he's actually worth hiring". And for god's sake don't add anything that gives them an excuse to reject you. Any firm worth working for is getting multiple applications for each place. If they see something that makes them go hmmmm, that allows them to trim the stack of the CV's down by one.

A:

I report mine just like another job:

1/200X - 12/201Y - SuperCoolStartup - Co-Founder and Technical Lead

Brief company description, including funding and other measurable forms
  of success
Brief description of management duties
Brief description of technical duties and technologies used

I also try to tailor my resume for each job. Sometimes I emphasize management duties, other time the technical solutions.

A:

Show your work.
The point of a resume is to convey what you've done in the past and what you will be able to do for your prospective employer.

List the startups that you've worked on just like you'd list any other job.
Explain the products developed in each case and how you contributed to them.
Talk about your responsibilities at each company, especially if they're relevant to the job that you're applying for.
Include the experience that you gained and skills that you used in each case.

The cover letter that you include with your resume is a good place to add relevant details about your experiences that don't easily fit into a resume.


Q:

echo an array in __toString method

I'm having a difficult time returning an array in my __toString method.
Here is my code.
public function __toString()
{
    $this->_libraries();
    $this->_sysConfig();

    //print_r($this->version);
    $version = implode("\n", $this->version);
    echo $version;
    return 'echo';//$version;
}

I have been playing around with it but no mater what I do I still get this error
Notice: Array to string conversion in (...)

Is it not possible to return an array?
this is the array i am trying to implode
Array
(
    [0] => Array
        (
            [version] => Array
                (
                    [item] => Array
                        (
                            [0] => Array
                                (
                                    [name] => cms
                                    [version] => 1.0
                                )

                            [1] => Array
                                (
                                    [name] => TinyMCE Jquery Package
                                    [version] => 3.5
                                )

                            [2] => Array
                                (
                                    [name] => Jquery
                                    [version] => 1.7.2
                                )

                        )

                )

        )

)

A:

You can not use implode on a multi dimensional array
Example
$version = Array (
        0 => Array (
                'version' => Array (
                        'item' => Array (
                                0 => Array (
                                        'name' => 'cms',
                                        'version' => '1.0'
                                ),

                                1 => Array (
                                        'name' => 'TinyMCE Jquery Package',
                                        'version' => '3.5'
                                ),

                                2 => Array (
                                        'name' => 'Jquery',
                                        'version' => '1.7.2'
                                )
                        )
                )

        )

);

$version = implode ( $version, "\n" );

Output
  Notice: Array to string conversion in xxxx

Demo 1
 $version = multi_implode ( $version, "," );

Output
 cms1.0 , TinyMCE Jquery Package3.5 , Jquery1.7.2

Demo 2
 $version = multi_implode ( $version, " , " ," = " );

Output
 cms = 1.0 , TinyMCE Jquery Package = 3.5 , Jquery = 1.7.2

Function Used
function multi_implode($pieces, $glue, $glue2 = null) {
    foreach ( $pieces as $piece ) {
        if (is_array ( $piece )) {
            $retVal [] = multi_implode ( $piece, $glue, $glue2 );
        } else {
            if ($glue2 == null) {
                $retVal [] = $piece;
            } else {
                $retVal [] = implode ( $glue2, $pieces );
                break;
            }
        }
    }
    return implode ( $glue, $retVal );
}


Q:

Property 'ensure' does not exist on type 'NodeRequire'

I'm trying webpack 2 code splitting.
According to this doc: https://webpack.js.org/guides/code-splitting-require/
the following code should include some.css into a new chunk named 'something'
require.ensure([], function(require) {
    require('some.css');
}, 'something');

but when I run it, I get this error:
ERROR in ./src/index.ts
(4,9): error TS2339: Property 'ensure' does not exist on type 'NodeRequire'.

Any idea about how to fix it?
Thanks

A:

The way I solved this was by creating my own interface - WebpackRequire - which extends NodeRequire with ensure1.
interface WebpackRequire extends NodeRequire {
  ensure(
    dependencies: string[],
    callback: (require: WebpackRequire) => void,
    errorCallback?: (error: Error) => void,
    chunkName?: string
  ): void;
};

If you've only got a single instance of require.ensure, you can then type cast it to a WebpackRequire using (require as WebpackRequire).ensure, but since I used it multiple times in a module, I created local require at the top scope of the module, type cast as WebpackRequire, like this:
const require: WebpackRequire = (window as any).require;

1I got the types of ensure from the Webpack docs


Q:

Load properties file within a web app

Up until now I was able to load the properties files via ClassLoader since it was a standalone app -> jar
/**
 * Path and filename for {@code.properties}.
 */
private String propertiesFileName = "./com/config/resources/config.properties";

propertiesFromFile.load(ClassLoader.getResourceAsStream(propertiesFileName));

Now I need to use this jar within a web app the problem is that via ClassLoader I get NULL
How can make that inside jar will be able to read is properties file ?
Is there I why via maven ?
Please advice
Thanks

A:

I experienced similar issues with different behaviours on different platforms when I use java.util.Properties. In the end I settled with using Apache Commons - Java Configuration API:-
PropertiesConfiguration properties = new PropertiesConfiguration("my.properties");
String propertyValue = properties.getString("prop.key");

The path to my properties files are set in my JVM classpath prefix when I start my container.


Q:

Date/Time not plotting as expected

I'm going to be plotting some temperature data over time and wrote a test program to see with Matplotlib can do for me.  When I plot the the date the date time does not display as I would expect, the date is output but the time is some type of counter not the time of day as expected.
Sample data:
import pandas as pd

df = pd.DataFrame([
    ['08/16/2019 00:00:00',70 ],['08/17/2019 00:05:00',70.5 ],
    ['08/17/2019 00:10:00',70.5],['08/17/2019 00:15:00',71 ],
    ['08/17/2019 00:20:00',72 ],['08/17/2019 00:25:00',73 ],
    ['08/17/2019 00:30:00',74 ],['08/17/2019 00:35:00',74.5],
    ['08/17/2019 00:40:00',75 ],['08/17/2019 00:45:00',74.5],
    ['08/17/2019 00:50:00',73 ],['08/17/2019 00:55:00',75 ],
    ['08/17/2019 01:00:00',72.5],['08/17/2019 01:05:00',78 ],
    ['08/17/2019 01:10:00',78]], columns=['Date Time', 'Temperature'])

df
Out[1]:
              Date Time  Temperature
0   08/16/2019 00:00:00         70.0
1   08/17/2019 00:05:00         70.5
2   08/17/2019 00:10:00         70.5
3   08/17/2019 00:15:00         71.0
4   08/17/2019 00:20:00         72.0
5   08/17/2019 00:25:00         73.0
6   08/17/2019 00:30:00         74.0
7   08/17/2019 00:35:00         74.5
8   08/17/2019 00:40:00         75.0
9   08/17/2019 00:45:00         74.5
10  08/17/2019 00:50:00         73.0
11  08/17/2019 00:55:00         75.0
12  08/17/2019 01:00:00         72.5
13  08/17/2019 01:05:00         78.0
14  08/17/2019 01:10:00         78.0

import csv
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime

path="/home/mikejs/PythonSandbox/temps.csv"
file = open(path,newline='')
reader = csv.reader(file)
header = next(reader)
dates = []
temps  = []

for row in reader:
    date = datetime.strptime(row[0],'%m/%d/%Y %H:%M:%S')
    dates.append(date)
    temps.append(float(row[1]))

plt.title("Temperatures Over Time")
plt.plot(dates,temps )
plt.ylabel('Temperatues')
plt.xlabel('Date/Time')
plt.xticks(rotation='45')
plt.tight_layout();
plt.savefig('temps.png')
plt.show()

A:

You can use matplotlib.dates module to transform your axis into dates and then it will interpret the spacing correctly.
Below is an example using pandas to reproduce your sample:
import pandas as pd
from matplotlib import dates as mdates

df = pd.DataFrame([
    ['08/16/2019 00:00:00',70 ],['08/17/2019 00:05:00',70.5 ],
    ['08/17/2019 00:10:00',70.5],['08/17/2019 00:15:00',71 ],
    ['08/17/2019 00:20:00',72 ],['08/17/2019 00:25:00',73 ],
    ['08/17/2019 00:30:00',74 ],['08/17/2019 00:35:00',74.5],
    ['08/17/2019 00:40:00',75 ],['08/17/2019 00:45:00',74.5],
    ['08/17/2019 00:50:00',73 ],['08/17/2019 00:55:00',75 ],
    ['08/17/2019 01:00:00',72.5],['08/17/2019 01:05:00',78 ],
    ['08/17/2019 01:10:00',78]], columns=['Date Time', 'Temperature'])

### make sure you set date as the index (and optionally drop the column)
df.index = pd.to_datetime(df['Date Time'])
df.drop(['Date Time'], axis=1, inplace=True)

Below I am plotting the sample data with the first observation and skipping it. As it is 24hrs ahead of the rest, you can notice the large spacing.
plt.figure(figsize=(16,6))
ax1 = plt.subplot(121)
ax1.set_title("Temperatures Over Time")
ax1.plot(mdates.date2num(df.index), df['Temperature'])
ax1.set_ylabel('Temperatues')
ax1.set_xlabel('Date/Time')
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m %H:%M"))
plt.xticks(df.index, rotation='45')

# fig, ax = plt.subplots()
ax = plt.subplot(122)
ax.plot(mdates.date2num(df[1:].index), df[1:]['Temperature'])
ax.set_title("Temperatures Over Time (skipping first)")
ax.set_xticks(df[1:].index)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m %H:%M"))
plt.xticks(rotation='45')
plt.tight_layout();
# plt.savefig('temps.png')
plt.show()

Also for editing the axis, it has a function to format it according to your needs. For instance in the following line you can adapt your format.
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m %H:%M"))


Q:

Custom Projection Operator using LINQ

We have created custom repository class to retrieve objects form entity framework context. Get method always returns whole object.
I wish to include project operator Select as parameter. So that we could pass from outside what needs to be selected & SQL query will be more efficient. Is it doable?
public class GenericRepository<TEntity> where TEntity : class
{
    internal DbContext context;
    public IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }
        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }
}

A:

Add params Expression<Func<T, object>>[] properties parameter(property selectors) to the method that does the querying, where T is the type of your Entity. Next call following method to get information about each property
private static PropertyInfo ResolveProperty<T>(Expression<Func<T, object>> property) where T : class
    {
        MemberExpression member;

        UnaryExpression body = property.Body as UnaryExpression;
        if (body != null)
        {
            member = (MemberExpression)body.Operand;
        }
        else
        {
            member = (MemberExpression)property.Body;
        }

        PropertyInfo info = (PropertyInfo)(member).Member;
        return info;
    }

Now, when you have information about properties, you may continue with custom implementation or make use of System.Linq.Dynamic
https://dynamiclinq.codeplex.com/


Q:

Multiple Language Website PHP

I want to make my PHP website into a multiple language website, with exactly two languages (English, Turkish).
At the top of the web page, there are two icons, one for English and the other for Turkish. When a user clicks on Turkish icon how can I detect that Turkish is selected?

How can I do that?
I have two files for languages,  one for English language and then another one for Turkish.
$arrLang['alert_admin_email_wrong']='kullanci email yanliştır '
$arrLang['alert_admin_email_wrong']='your email is wrong  '

I must use session or cookies for this problem

A:

The easiest way to do that is to create an cookie when the user clicks on the wanted language.
As for the array i would split it per language
$arrLang['en']['alert_admin_email_wrong'] = 'text here';
$arrLang['tr']['alert_admin_email_wrong'] = 'text here turkish';

As for language selection would do this on the webpage
EnglishTurkish

On the language selection page :
$defaultLanguage = isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'en'; //default to english language
if(isset($_GET['langSelect'])){
    //allow only 2 for now ( english / turkish)
    $langForSelection = "";
    switch($_GET['langSelect']){
        case 'en':
        $langForSelection = 'en';
        break;
        case 'tr':
        $langForSelection = 'tr';
        break;
        default:
        break;
    }
    if(isset($langForSelection)){
        setcookie('lang',$langForSelection,time()+24*7*60*60);//set cookie to expire in 7 days
    }
}

After to show the variables
echo $arrLang[$defaultLanguage]['alert_admin_email_wrong'];


Q:

Change the extension of previous uploaded files using Django

models.py
class Entry(models.Model):
    owner = models.ForeignKey(User, related_name='owner')
    myfile = models.FileField(upload_to='my_files/%Y/%m/%d')

I need to change the extension of previously uploaded files using this model.

A:

Note that upload_to can be callable, like this:
import date
import os
def upload_path(instance, filename):
    d = date.today()
    parts = os.path.splitext(filename)
    return 'my_files/%s/%s/%s/%s.%s' % (
        d.year, d.month, d.day, parts[0], 'new_ext')

So, in your model:
class Entry(models.Model):
   # ...
   myfile = models.FileField(upload_to=upload_path)

This won't help you to handle files already uploaded in past, but new uploads will have correct names.


Q:

Difference between two sets of the Tur

A pretty popular set of the Tur is the Shirat Devorah edition. It has a beautiful typeface, corrected girsaos, useful features like Seif indicators, summaries of each simman, notes from achronim, etc.
I recently saw in a shul a different set by Meor. It's also a beautiful set, and seems to have similar features. They're also around the same price.
What do people recommend? Has anyone used both? What's the difference between the two? Does one set have a must have feature the other doesn't have?

A:

Different strokes for different folks. I personally prefer SD. I've used both but the HaMaor only when I don't have the SD. Some differences: SD sticks to basic textual corrections and critical (and sometime classical) glosses on Tur & commentaries; very "non-crowded" pages; doesn't carry itself like an encyclopedia. On the other hand, I find HaMaor to contain: while they too "clean" the texts on the page I find their notes to have too many unnecessary "round ups" of commentaries at the bottom of each page; formatting of pages feel dizzying (like the Oz VeHadar gemara); compilation at the end of each volume is more for reference type - something I find dispensable, unlike the compilation of Mechon Yerushalayim's Shulchan Aruch. In summation: the two editions cater to different folks. It boils down to the reader's preference.
Alternatively, see עט סופר's review here (I second his sentiments):
http://forum.otzar.org/viewtopic.php?t=6298


Q:

how to extract the column name and data type from nested struct type in spark

How to extract the column name and data type from nested struct type in spark
schema getting like this:
(events,StructType(
   StructField(beaconType,StringType,true),
   StructField(beaconVersion,StringType,true),
   StructField(client,StringType,true),
   StructField(data,StructType(
      StructField(ad,StructType(
         StructField(adId,StringType,true)
      )
   )
)

I want to convert into below format
Array[(String, String)] = Array(
  (client,StringType),
  (beaconType,StringType),
  (beaconVersion,StringType),
  (phase,StringType)

could you please help on this

A:

Question is somewhat unclear, but if you're looking for a way to "flatten" a DataFrame schema (i.e. get an array of all non-struct fields), here's one:
def flatten(schema: StructType): Array[StructField] = schema.fields.flatMap { f =>
  f.dataType match {
    case struct: StructType => flatten(struct)
    case _ => Array(f)
  }
}

For example:
val schema = StructType(Seq(StructField("events",
  StructType(Seq(
    StructField("beaconVersion", IntegerType, true),
    StructField("client", StringType, true),
    StructField("data", StructType(Seq(
      StructField("ad", StructType(Seq(
        StructField("adId", StringType, true)
      )))
    )))
  )))
))

println(flatten(schema).toList)
// List(StructField(beaconVersion,IntegerType,true), StructField(client,StringType,true), StructField(adId,StringType,true))


Q:

Why am I getting erroneous records in a Query-of-Queries with LIKE conditions?

I have an ColdFusion 8 application that caches a large query every 2 minutes using a Scheduled Task. This query contains product data. This data is used in AJAX calls for auto-complete logic, which is the primary reason it is cached, since it takes a few seconds to run each time.
In the application, there are several pages that query from this query result using Query-of-Queries.
On of these queries uses a LIKE condition to filter the results. However, the query is returning records that do not meet the conditions. Why is this happening and how can I prevent it?
My Cached Query:
<cfquery name="qProducts" datasource="#APPLICATION.DataSource#">
    SELECT
        P.SKU
        P.DESC,
        P.TITLE,
        P.KEYWORDS,
        X.ATTR1
    FROM    PRODUCTS P
        LEFT JOIN PRODUCTSEXT X
            ON P.SKU = X.EXTSKU
    WHERE   P.ACTIVE = 1
</cfquery>

My Filter Query:
<cfquery name="_qFilteredProducts" dbtype="Query">
    SELECT
        SKU
        DESC,
        TITLE,
        KEYWORDS
    FROM    qProducts
    WHERE   1 = 1
        AND (
                DESC LIKE '%#searchstring#%'
            OR  TITLE LIKE '%#searchstring#%'
            OR  KEYWORDS LIKE '%#searchstring#%'
            OR  ATTR1 LIKE '%#searchstring#%'
            )
</cfquery>

So, let's say I pass in the value "gold" for searchstring.
I am seeing results like the following:
SKU               DESC                TITLE         KEYWORDS
-------------------------------------------------------------------------------
ABC               GOLD KEY            GOLD KEY      GOLD KEY SHINY
DEF               SILVER KEY          SILVER KEY    SILVER KEY SHINY

I should not see that second record.

A:

I think I figured this out by doing a little more research on the internet. My original query actually has a LEFT JOIN in it, and the LIKE clause in ColdFusion's QoQ tends to completely ignore NULL values, so I simply had to update my original/database query to change all NULL values to empty string.
<cfquery name="qProducts" datasource="#APPLICATION.DataSource#">
    SELECT
        P.SKU
        P.DESC,
        P.TITLE,
        P.KEYWORDS,
        IFNULL(X.ATTR1, '')
    FROM    PRODUCTS P
        LEFT JOIN PRODUCTSEXT X
            ON P.SKU = X.EXTSKU
    WHERE   P.ACTIVE = 1
</cfquery>


Q:

Rails 3.1 remote requests submitting twice

I developed a Rails 3.1 application that consists of a 100% Ajax CRUD forms to input users and customers.  I created two separate models, controllers, views etc.  The views for each model contain jquery files for create edit update and destroy.  The problem is when I perform any operation that performs a remote operation, it is called twice.  I can confirm this happening in console view in firebug as well as output in WEBrick output.  Can anyone assist in tracking down what happened here? What would cause rails to process each call twice?

A:

Adding config.serve_static_assets = false to development.rb will prevent loading files from /public/assets.
Actually I need to precompile locally because my test mode is using only static assets from /public/assets - tests are catching possible production asset problems. How? Just set config.assets.compile = false and config.serve_static_assets = true in test.rb configuration.

A:

If you have precompiled the assets and running in development mode, then the JavaScripts will be included twice on the page.
Remove everything from public/assets if in development mode.


Q:

What is the "abomination of desolation"?

"'Therefore when you see the abomination of desolation which was spoken of through Daniel the prophet, standing in the holy place (let the reader understand)'"  (Matthew 24:15, NASB)

I don't understand.
I'm just curious if anyone actually understands this?  Is this the Antichrist, or Jesus, or the Jews, or Rome...?  Is this a prophecy that will only be understood once it happens?  Make your case.  (See Daniel 9:27, 11:31, and 12:11.)

A:

Christians of many persuasions recognize this text as a definite and peculiar sign concerning the last days. Yet even though the majority of them can agree that the abomination of desolation is an important sign, they can't seem to agree on its specific nature. Even preachers are thrown into a quagmire of confusion - looking for something that no one is very sure about. It is a perfect example of the blind leading the blind.
Of course, some believe they know the identity of the abomination of desolation. Some teach that this prophecy was fulfilled when Antiochus Epiphanes interrupted the temple sacrifices between 168 and 165 B.C. The abomination they point to is the pig Antiochus had offered on the altar in the temple complex. Others believe the abomination of desolation refers to a future time when an atheistic anti-christ will overthrow the temple in Jerusalem and use it as his throne. Then there are those who believe the abomination of desolation is the Roman standards which were worshiped in Jerusalem in 70 A.D. at the time of its destruction by Titus.
Just what exactly is the abomination of desolation? Is it any one of these alternatives? Is it all of them at the same time? Or could it be possible that not any of these interpretations are correct? The answer to these questions is vitally important. Jesus clearly implies that our very lives could be at stake over this matter.
Jesus tells us that our study of the abomination of desolation should focus on the book of Daniel (Matthew 24:15). When one makes a careful study of this book, he discovers that the abomination of desolation can be divided into three parts. These parts are: the abomination of desolation in Daniel's day (involving the first temple); the abomination of desolation in Jesus' day (involving the second temple); and finally the abomination of desolation in the time of the end (involving the whole Christian church). The issues that come into play in the abomination of desolation as treated in the book of Daniel remain consistent in each of its three phases. Therefore they are types, or examples, of each other.
The First Abomination
The key that unlocks the mystery of this prophetic event is found in the first two verses of Daniel.

In the third year of the reign of Jehoiakim king of Judah came
Nebuchadnezzar king of Babylon unto Jerusalem, and beseiged it. And
the Lord gave Jehoiakim king of Judah into his hand, with part of the
vessels of the house of God: which he carried into the land of Shinar
to the house of his god; and he brought the vessels into the treasure
house of his god (Daniel 1:1,2).

In these two short sentences Daniel provides a concise historical background to the remainder of the book which follows.
Further study of Daniel's prologue reveals the abomination of desolation was existent in his time and led to Jerusalem's captivity. The Chronicler reveals the reason the Jewish kings fell to Babylon.

"Jehoiakim was twenty and five years old when he began to reign... and
he did that which was evil in the sight of the Lord his God."

It was because of Jehoiakim's iniquitous life that God allowed him to be taken captive.
The significant feature of this is that Jehoiakim's evil deeds are described this way:

"Now the rest of the acts of Jehoiakim, and his abominations which he
did, and that which was found in him, behold, they are written in the
book of the kings of Israel and Judah: and Jehoiachin his son reigned
in his stead" (2 Chronicles 36:5-8).

It was specifically the abominations of Jehoiakim that led him and his city to forfeit God's protection and thus fall to Nebuchadnezzar.
Unfortunately Jehoiachin, his son, didn't do much better. Scripture tells us he also did "that which was evil in the sight of the Lord." Consequently he too was taken captive to Babylon, and "Zedekiah his brother" was placed as king over Judah and Jerusalem (v. 9-11).
The Bible goes on to record that not only did Zedekiah turn out to be just as evil as his two predecessors, but "moreover all the chief of the priests, and the people, transgressed very much after all the abominations of the heathen" (v. 12-14). God's political and religious leaders, as well as the people, adopted heathen ways as their own. They did this at the expense of God's revealed truth. Notice where these abominations were committed: the people "transgressed very much after all the abominations of the heathen; and polluted the house of the Lord which he had hallowed in Jerusalem" (v. 14). These abominations were standing in God's consecrated holy place, the "house of the Lord." The religious leaders of the day had purposefully led the people to adopt heathen worship practices and incorporated them into their worship of God. In substituting for God's commandments the vain notions of men, the leaders of God's heritage provoked his wrath. The people rejected God's calls to repentance and reformation and were left to reap the consequences. "Therefore, he brought upon them the king of the Chaldees, who slew their young men with the sword in the house of their sanctuary" (v. 17).
This judgment was felt not only in the spilling of the blood, but in the complete destruction of the city and sanctuary (v. 19). This all was done "To fulfill the word of the Lord by the mouth of Jeremiah, until the land had enjoyed her sabbaths: for as long as she lay desolate she kept sabbath to fulfill threescore and ten years" (v. 21). The result of God's people practicing the religious abominations of the heathen was the desolation of their land, city and sanctuary.
Breaking The Sabbath Brought Desolation
Just what were these abominations that resulted in such desolation? Since this was all done "To fulfill the word of the Lord by the mouth of Jeremiah," then Jeremiah should be able to tell us what substitutions in worship had been made. In Jeremiah 17 the prophet is told to stand in the gate of the people and prophesy. Under a divine mandate, Jeremiah told the people that if they would honor God's seventh-day Sabbath their city would remain forever, and that this faithful obedience would lead them into such a relationship with Himself that they would be used to convert the surrounding heathen nations (ch. 17:19-26).
On the other hand, if they would not keep the Sabbath day holy God would allow their city to be desolated. "But if ye will not hearken unto me to hallow the Sabbath day, and not to bear a burden, even entering in at the gates of Jerusalem on the Sabbath day; then I will kindle a fire in the gates thereof, and it shall devour the palaces of Jerusalem, and it shall not be quenched" (v. 27).
Sadly, the Jews chose to continue breaking God's Sabbath and thus inaugurated their own destruction and captivity. The abomination that led to their desolation was breaking the Sabbath. Thus, we see the significance of 2 Chronicles 36:21:

"To fulfill the word of the Lord by the mouth of Jeremiah, until the
land had enjoyed her Sabbaths: for as long as she lay desolate she
kept Sabbath."

Ezekiel, who lived during the same time, also tells us about the abominations God's people were practicing in the holy place. In Ezekiel 8, the prophet was brought by vision to the door of the inner gate. God proceeded to show his servant the progressively greater outrages His people were committing. In verses 5 and 6 He speaks of an image that provoked Him to jealousy. In an escalation of outrage, unclean beasts had been brought into the house of God, women were weeping for Tammuz and the greatest abomination of all was twenty-five men standing in God's holy place "with their backs toward the temple of the Lord, and their faces toward the east; and they worshipped the sun toward the east" (Ezekiel 8:16).
God had instructed the Jews to erect the temple in a manner that would discourage the imitation of their heathen neighbors in sun worship. The ark of the covenant, the very focal point of the Jews' worship, was placed at the western end of the tabernacle. Thus the children of Israel would face the west, their backs to the rising sun, when they worshipped the true God. Yet the entrance of paganism among God's people had grown to such proportions that Judah's leading men were actually turning their backs on the temple of God. This was a significant act of apostasy.
Both Ezekiel and Jeremiah list the heathen practices that had been incorporated into the worship of God. Whether it was breaking the second commandment by idol worship, adoring unclean beasts, worshipping Tammuz, the mythological god of the pagans, or breaking God's holy Sabbath and worshiping the sun on the day consecrated to it, these practices all were classed by God as abominations. It was because the Jews persisted in justifying their own course and continued in these heathen customs that God permitted the desolation of their city.
Daniel himself agrees that it was the sins committed by God's people that caused their desolation.

"O Lord, according to all thy righteousness, I beseech thee, let thine
anger and thy fury be turned away from thy city Jerusalem, thy holy
mountain: because for our sins, and the iniquities of our fathers....
cause thy face to shine upon thy sanctuary that is desolate.... open
thy eyes, and behold our desolations..." (Daniel 9:16-18).

It is important to note that the abominations were done by the apostate people of God. This in turn resulted in their forfeiture of God's protection and called down His judgments and chastisement in their desolation. This scenario of the abomination of desolation in Daniel's day, involving the first Jewish temple period, prefigures the two other abominations of desolation prophesied in Daniel. The next one we shall consider is the one that concerns the second Jewish temple period.
The Second Temple Desolated
After their release from Babylonian captivity and rebuilding the city and temple, the Jewish leaders erected a mountain of rules and regulations designed to protect them from repeating the sins that had led to their bondage. The fourth commandment's seventh-day Sabbath became a special object of amendment. The Jews reasoned that since it was transgression of the Sabbath that led to their captivity, they needed to define in minute detail how the Sabbath should be kept.
Over 500 rules concerning Sabbathkeeping eventually resulted. Some of these Sabbath laws were as ridiculous as this: one could not leave an egg in the sun on the Sabbath because the sun might cook it, and cooking on the Sabbath was a violation of the fourth commandment. Of course, this only resulted in a system of pure legalism. At last the people began to believe that favor with God depended on how well they obeyed the traditions of their elders.
Ultimately the people were led full circle to disobedience again. Jesus comments that in spite of their apparent religiosity they were still breaking God's law even as their forefathers had during Isaiah's and Daniel's day.

"Well hath Isaiah prophesied of you hypocrites, as it is written, This
people honoreth me with their lips, but their heart is far from me.
Howbeit in vain do they worship me, teaching for doctrines the
commandments of men. For laying aside the commandment of God, ye hold
the tradition of men... full well ye reject the commandment of God,
that ye may keep your own tradition... making the word of God of none
effect through your tradition, which ye have delivered" (Mark 7:6-13).

Once again the people found themselves immersed in vain and rebellious worship.
Even though their apostasy expressed itself in legalism instead of laxness, it was still based on the same principle upon which all pagan religions are based - that man can save himself by his own works. Jesus, like Jeremiah of old, rebuked this religious system and called it an abomination.

"Ye are they which justify yourselves before men; but God knoweth your
hearts: for that which is highly esteemed among men is abomination in
the sight of God" (Luke 16:15).

Jesus expressed His displeasure for their abominations on numerous occasions. Most notable were the two times He cleansed the temple. On these times He expressed His anger at the desecration of His holy place. The controversy between Jesus and the Jews steamed, boiled and spewed over religion. The religious leaders hated Him because He didn't look like the Messiah, He didn't respect their traditions and most notably He didn't keep the Sabbath in the manner they thought it should be kept. This latter issue infuriated the Jews and led them to seek Jesus' death (See John 5:10-16; Matthew 12:1-4; Mark 3:1-6).
In spite of the religious leaders' resistance, Jesus sought time and again to bring them to repentance and reformation. Often He reproved them for their erroneous ways and pointed the way to true and undefiled religion that is of great price in the sight of God. Yet they hardened their hearts and beat back the waves of God's mercy.
As Jesus entered Jerusalem for the last time, His prophetic eye saw the consequences of their constant rebellion. With a grief-stricken heart and tears coursing down His cheeks, He prophesied the coming doom of the city:

"For the days shall come upon thee, that thine enemies shall cast a
trench about thee, and compass thee round, and keep thee in on every
side and shall lay thee even with the ground, and thy children within
thee; and they shall not leave in thee one stone upon another; because
thou knewest not the time of thy visitation" (Luke 19:41-44).

After teaching in the temple for several days, Jesus left its precincts for the last time. Again He was choked with anguish as He saw the ultimate result of His people's apostasy. He exclaimed,

"O Jerusalem, Jerusalem, thou that killest the prophets, and stonest
them which are sent unto thee, how often would I have gathered thy
children together, even as a hen gathereth her chickens under her
wings and ye would not! Behold your house is left unto you desolate"
(Matthew 23:37,38).

On both these occasions Jesus placed the guilt upon the people by stating, "they knew not the time of their visitation" and "ye would not." As a result of not responding to God's call to turn from their abominations, their temple was to be desolated. This prophecy was fulfilled in 70 A.D. when the Roman armies of Titus burned the temple to the ground. This second desolation of the temple perfectly paralleled its first destruction. On both occasions the abominations were done by the apostate people of God and the desolation was an act of judgment performed by a heathen army.
This desolation of Jerusalem was prophesied by Daniel to come as a result of the people rejecting Messiah the prince. A careful study of Daniel 9:25-27 will show this to be the case. In verse 25 Messiah is promised to Israel and the city's restoration is also predicted. But then, ominously, all is prophesied for doom again. Verse 26 speaks of Messiah being killed by His own people and of how this act would cause their city and sanctuary to be desolated once again.
As Daniel heard Gabriel relay this prophecy, it was to his mind a replay of what he had seen happen to the Jerusalem of his day. The prophecy indicated that history would repeat itself, and this is exactly what happened. The abominations that God's people committed resulted, in both 586 B.C. and 70 A.D., in the destruction of their sanctuary and city -- first by Nebuchadnezzar, then by Titus.
Because Israel rejected the Messiah they lost their place as God's favored people. Jesus predicted this would take place by saying, "The kingdom of God shall be taken from you, and given to a nation bringing forth the fruits thereof" (Matthew 21:43). Israel forfeited their franchise of the gospel by their own obstinate sin.
Who would be the new nation to receive the kingdom of God and bring forth the fruits thereof? The Bible provides a clear and concise answer in the apostle Peter's letter to the Gentile converts who "In time past were not a people, but are now the people of God." Of the converts to Christianity, the new people of God, he further says, "But ye are a chosen generation, a royal priesthood, an holy nation, a peculiar people; that ye should shew forth the praises of him who hath called you out of darkness into his marvelous light" (1 Peter 2:9,10).
In the new dispensation God bestows upon the converted Christians all the privileges and promises that had been made to the literal seed of Abraham (see Galatians 3:26-29). Now converted Christians assume the role of Israel, and the Christian church absorbs the status of the temple or sanctuary of God. The Scriptures make this abundantly clear in such texts as Romans 2;28,29; Ephesians 2:11-13; 19-22; and 1 Peter 2:5.
The Final Desolation
It is in the light of this New Testament principle of spiritual Israel that Daniel speaks of the abomination of desolation the third and final time. These references can be found in Daniel 8:13; 11:31; and 12:11. Discerning students of prophetic history realize that these verses predict the formation and ascension of power by the Papacy. It is an indisputable fact of history that the Papacy brought into the Christian church the very same practices of paganism for which ancient Jerusalem was destroyed. One has to do only a little study to see how image worship, Tammuz worship, and sun worship were introduced to Christianity during the Dark Ages. Many of these abominations are still with us in the form of statues, candles for the saints, rosary beads, Easter sunrise services and Sunday worship. [For more information on this subject, see Amazing Facts' booklet Baptized Paganism.]
By no means does the papal apostasy exonerate Protestantism. Most Protestant churches accede to the apostasy by continuing the practice of abominations that have their roots firmly fixed in ancient pagan religions, which were established to destroy God's truth. Both Catholicism and Protestantism have fostered abominations in God's holy place, His church. The Christian church is mirroring literal Israel. We are repeating many of the same sins and will consequently reap the same punishment of desolation, unless we are willing to read the handwriting on the wall and flee from Babylon.
It is clear that the three occasions of abomination of desolation found in Daniel result from apostasy on the part of God's people, but what is the sign that will tell us when the desolation is nigh?
In Luke 21:20 Jesus told His disciples what would be the last sign of the imminent destruction of Jerusalem. He said, "And when ye shall see Jerusalem compassed with armies, then know that the desolation thereof is nigh." This text does not indicate that the armies are the abomination, but rather that the armies were the instrument to cause desolation. Through the Roman armies God would execute "the days of vengeance" for Israel's abominations.
When the Roman armies surrounded Jerusalem, it was a sign that most of the city's leaders and inhabitants had passed the boundaries of grace and had filled their cup of iniquity. To the Christians living in the city, this was to be a sign that Jerusalem would soon suffer God's judgment. As soon as the first opportunity arose, these Christians were to "flee to the mountains" (v. 21). In 66 A.D. when Cestius, the Roman general, surrounded the city the Christians knew the promised sign had arrived and the time had come to flee. At their first opportunity to escape they did so, and not one Christian died in the horrible destruction of Jerusalem in 70 A.D.
Just as God gave the early Christians a sign of when to flee Jerusalem, so He has given us a sign. He has made it possible for every Christian to know when this world's probationary hour is nearing its close.
In Revelation 13 and 14 John records a list of omens that will tell us just how close we are to the end. The sign that will show this nation has filled its cup of iniquity will be when it makes an image to the Papacy by uniting church and state. How much more neatly could this be effected than by the passage of a national Sunday law commanding everyone to honor a pagan day of worship? Such an event will be a direct fulfillment of Revelation 13:15-17, and provide assurance that the end of this earth's time is quickly approaching.
One author describes coming events this way: "As the approach of Roman armies was a sign to the disciples of the impending destruction of Jerusalem, so may this apostasy be a sign to us that the limit of God's forbearance is reached, that the measure of our nation's iniquity is full, and that the angel of mercy is about to take her flight." When the churches have apostasized in their abominations to such a degree that they enact legislation of a religious law which displaces God's holy Sabbath with a pagan holiday, we may leave our cities, knowing that a time of trouble will be forthcoming.
The abomination of desolation is an important subject in these last days. If we study this prophecy carefully, we will find that in each of its three fulfillments refers to a national apostasy by God's people that ends in their tragic destruction. We are now living in the time of the Christian church's final apostasy, which makes of none effect the commandments of God. We need to see that we are in the midst of fulfilling prophecy and keep our eyes open for the culmination of all things.
Our only sure protection against the abomination of desolation is to give our lives unreservedly to Jesus, loving others as He loves them and worshiping Him in the way that His word teaches. The greatest commandment is simply to love God with all our heart and soul and strength. If we have such love, it will be natural for us to do all things to please and honor Him. In return, He will see us safely through the desolation that will close this earth's history just before He comes again.

A:

From an Orthodox source we have:

There is no doubt that these words of Jesus found their partial
  fulfillment when Titus placed an idol on the site of the burned Temple
  after destroying Jerusalem, however, it is equally doubtless that the
  Lord was also alluding to the end of the world ...

But later, the author quotes some Fathers thusly:

According to Irenaeus, Hippolytus of Rome, Cyril of Jerusalem, Origen,
  and Cassian, the “Abomination Of Desolation spoken of by Daniel the
  prophet” is none other than Antichrist, who must appear before the
  second coming of Christ, seduce the world by his false miracles,
  causing the final apostasy, and who will “sit in the temple of God
  (the holy place), showing himself that he is God.” (II Thes 2:4)

So it seems to imply a sign of the / an antichrist (recall that John says there are 'indeed many antichrists already among you')
The source is here: http://www.stmaryscopticorthodox.ca/legacy/publications/books/books.html
But the Fathers cited are commonly available here:
http://www.ccel.org/fathers.html
The eschatological references are these:

Second, the information concerning the Abomination Of Desolation, and
  the following instructions to flee it in an urgent manner, are
  immediately followed by this verse, “For then shall be great
  tribulation, such as was not since the beginning of the world to this
  time, no, nor ever shall be.” (Matt 24:21) From this, it is safe to
  assume that the Abomination Of Desolation will be manifested standing
  in the “holy place” during the “Great Tribulation” mentioned in the
  Book of Daniel 12:1, as well as the Book of Revelation 7:14.


Q:

Access denied issue when tried to copy from remote machine to local through batch file

Steps:
Machine A

running a batch file to connect to machine B and run a batch file(test.bat) on it
Machine B

test.bat
The copy command I am using:
copy text.txt \\Machine A\shared folder\test.txt (I am able to access this batch files but copy is giving access denied error)
Any ideas what I am doing wrong?

A:

Your batch file located on machine B is running on machine A. Just copy the file in the batch on machine A
copy "\\machineb\C$\folder\file.txt" "c:\somefolder\somefile.txt"

C$ is the default share for admins. Use whatever sharename is appropiate.


Q:

$K:=\int_{-\pi/2}^{\pi/2} {1+\sqrt{\cos(x)}}dx$ integral $K.M.N$ Who is the biggest and who is the smallest?

Set
   $$M:=\int_{-\pi/2}^{\pi/2}\frac{((1+x)^2)}{(1+x^2)}dx$$
$$N:=\int_{-\pi/2}^{\pi/2}\frac{(1+x)}{(e^{x})}dx$$
$$K:=\int_{-\pi/2}^{\pi/2}  {1+\sqrt{\cos(x)}}dx$$
integral $K.M.N$ Who is the biggest and who is the smallest?

A:

It is easy to see that:$$M=\pi,N<\pi,K>\pi.$$
Please note that:
$\frac{((1+x)^2)}{(1+x^2)}=1+\frac{2x}{1+x^2},$ $\frac{1+x}{e^x}<1$, $1+\sqrt{\cos(x)}>1$.


Q:

animated HTML/CSS/jQuery Skills Graph

So I am trying to make a 'skills' graphic that loads up when the page is opened.
Using html, css, and jquery; but I cannot figure out why the little progress bars won't display the load action.I'm hoping someone can lead me in the right direction (hint) or find out whats wrong!
Here it is:
Fiddle
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Skills</title>

adobe creative suite cc

html5

css3/css

jquery

javascript

bootstrap

wordpress

user interface (ui)

user experience (ux)

responsive web design

mobile app design

rapid prototyping

A:

it looks like you forgot to set background and height to the ".progress-bar".
so, your css code should embed:
.progress-bar {
    height: 20px;
    background-color: #f00;
}

here is your exmaple


Q:

Watir timing out when trying to find any elements after visiting webpage

So probably the most important thing to preface this with is that I'm using c9.  It's an IDE in the cloud and so that is giving me a lot of trouble when trying to use Chrome or Firefox with Watir, because I can't write a path to the Chrome or Firefox browser.  I've also tried every variation of wait methods I could find but none of them work.
def save
    require 'watir'
    require 'phantomjs'

    @browser = Watir::Browser.new :phantomjs
    @browser.goto "https://kroger.softcoin.com/programs/kroger/digital_coupons/?origin=DigitalCoupons&banner=Smiths#contentBox"

    @browser.div(id: "contentBox").wait_until(&:present?).text
    @products = @browser.divs

end

Error
timed out after 30 seconds, waiting for true condition on #"contentBox", :tag_name=>"div"}>
The way I want to fix this problem of not being able to scrape data from the Smiths website is to use a chrome browser, but I get the error "unable to connect to chromedriver 127.0.0.1:9515"

A:

I had similar problem
and I resolved it by installing docker container with selenium
# docker-compose.yml file
version: '2'
services:
  selenium:
    image: selenium/standalone-chrome
    ports:
      - "4444:4444"
    restart: always
    volumes:
      - "${PWD}/spec:${PWD}/spec" # I exposed `spec` dir to cover code with specs
      - /dev/shm:/dev/shm

# test.rb file
@browser = Watir::Browser.new(
  :remote,
  url: 'http://localhost:4444/wd/hub'
)

Run container with command:
docker run -it -d -P -p 4444:4444 -v `pwd`/spec:`pwd`/spec selenium/standalone-chrome

And try again
(Also you can run container even on VPS or another remote server, and then connect to it)


Q:

NSArrayController, creating CoreData entities programmatically, and KVO

I have an NSTableView whose NSTableColumn's value is bound to an NSArrayController.  The arrayController controls a set of entities in my core data managed object context.
It works well, and when new entities are inserted into the arrayController via UI Actions the tableView selects the new item.
However I would to create new entities into the moc programmatically, then select the new object in the arrayController.
I have tried the following:
Image *newImage = [Image newImage]; // convenience method to insert new entity into mod.
newImage.title = [[pathToImage lastPathComponent] stringByDeletingPathExtension];
newImage.filename = [pathToImage lastPathComponent];

[self.primaryWindowController showImage:newImage];

The showImage: method is as so:
- (void)showImage:(Image *)image
{
    [self.imagesArrayController fetch:self];
    [self.imagesArrayController setSelectedObjects:@[image]];
}

However, the arrayController doesn't change its selection.
Am I doing it wrong?  I assume that the newImage object that I created in the moc is the same as the object that the arrayController is controlling.  If that's true, why isn't the arrayController changing its selection?
Hmm - testing that assumption, I have now checked the contents of the arrayController at runtime.  The new image is not present - which I assume means that I have 'gone behind the back' of the bindings by manually inserting into the moc...
My newImage convenience method is as so:
+ (Image *)newImage
{
    Image *newImage = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:[[CoreDataController sharedController] managedObjectContext]];
    return newImage;
}

Is that not KVO compliant?
hmmm - Edit 2...
I assume that it is KVO compliant, as the new image appears in the UI.  I'm now thinking that there is a delay between inserting the entity into the moc and the arrayController being informed.
I See from this question New Core Data object doesn't show up in NSArrayController arrangedObjects (helpfully shown to the right of this question by SO) that asking the arrayController to fetch: should help update the  arrayController, but that the actual fetch: won't happen until the next time the runloop runs.
Should I delay the selection of the new object using a timer?  That seems a little inelegant...

A:

Right - solved it, thanks to this question: New Core Data object doesn't show up in NSArrayController arrangedObjects
I had to call processPendingChanges: on the moc directly after inserting the new object.
So, my new creation convenience method is now:
+ (Image *)newImage
{
    Image *newImage = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:[[CoreDataController sharedController] managedObjectContext]];
    [[[CoreDataController sharedController] managedObjectContext] processPendingChanges];
    return newImage;
}


Q:

Angular input event is not fired by setting the value with the model

I use a input field which calls a method when the value in it changes. But when I set the value in the input field by the ngModel (not typed by hand) the "value changed" event of the input field will not be fired.
Input field:
<div>
  <input type="text" id="orderNumberFilter" (input)="updateOrderNumberFilter($event)" [(ngModel)]="orderNumberFilterValue">
</div>

component:
public updateData(evt: any): void {
  .finally(() => {
    this.orderNumberFilterValue = "test"
  })
  .subscribe(
    //get data from backend
  });
}

public updateOrderNumberFilter(evt: any): void {

 //do stuff with the event

}

A:

And it will not be fired, because input event will be fired only during user interaction.
You can work with Reactive Forms instead of Template Driven Forms and using its valueChanges function you can listen to changes of the value of the controls.
Another answer about Reactive Form value changes you can read here
UPDATED
You can declare your function to get the value of the input
public updateOrderNumberFilter(value: any): void {

}

In the markup attach it with $event.target.value
<input type="text" id="orderNumberFilter" (input)="updateOrderNumberFilter($event.target.value)" [(ngModel)]="orderNumberFilterValue">

and also call it in the finally and pass the value.


Q:

Power Apps - Create a collection

I have 4 labels defined like this,
Cat10
Cat21
Cat32
Cat45

and I have 4 corresponding text inputs defined as,
TextInput 10  (Takes only a number)
TextInput 21  (Takes only a number)
TextInput 32  (Takes only a number)
TextInput 45  (Takes only a number)

The User manually inputs the TextInputs and I want to do a bar graph of these numbers against the corresponding category while he is entering. How do I go about it. I did some research it says creating a collection is the only way. But couldn't solve it on my own. Kindly help me with this.
For example my collection will have 4 rows,
Category    Value
Cat10       10
Cat21       12
Cat32       21
Cat45       30

The number of rows will not increase, every time the user changes a value it will always update the existing one.

A:

The ClearCollect function should cover your need.
With the information you offered please try the below-listed formula
ClearCollect(
CustomCollection,
{
    Category: "Cat10",
    Value: TextInput10.Text
},
{
    Category: "Cat12",
    Value: TextInput12.Text
},
{
    Category: "Cat21",
    Value: TextInput21.Text
},
{
    Category: "Cat45",
    Value: TextInput45.Text
})

CustomCollection is the name of the collection you would like to store. So, you can, of course, go for a different name!
You can find more information about the ClearCollect function on the official Microsoft help page.
Click here


Q:

Are there video games in the Star Trek universe?

I am finishing up the Star Trek: The Next Generation episode "The Game," wherein the crew of the Enterprise get addicted to a virtual reality headset game involving putting a disk in a cone. It is incredibly dated CGI.

This game doesn't appear to be more thrilling than the games that existed when this episode was aired (1991), and TNG takes place in the distant future. Is no effort put into video game design and video games in general? Does anyone in the Star Trek universe mention video games or play them? Is there any reason other than the game's addictiveness that they are they so enthralled by putting disks in cones?

A:

That particular game is more enthralling because it gets you high, and has some mind-control elements.  The plot for that episode involves Riker on vacation receiving the game from a lady friend of his.  He gets hooked, takes it back to the Enterprise and shares with with all of the crew.  Wesley and his lady friend don't play it, see everyone else becoming mind-controlled podpeople, and save the Enterprise by getting everyone deprogrammed.  At the end of the episode, Riker's lady friend shows up, expecting the crew of the Enterprise to be under her control.
To answer the rest of your question, yes video games still exist.  There are games in the holodeck/holosuite.  Beyond just using the holodeck/holosuite as a simulated field for games to be played (i.e. making a baseball field, or the 3D racquetball game Miles and Bashir play), the Vic Fontaine arc where his casino is taken over by a rival is essentially a sort of Sim-casino game.  In addition, I recall a DS9 episode where Rom got hooked on a handheld game that Nog owned, but can't recall more details on that.
There's also dialogue at the start of the DS9 episode Blood Oath where Quark mentions a Klingon battle being played out in a holosuite. The key thing is that the person using the holosuite keeps losing the battle. The ability to lose is a commonplace component of video games, as it is a way to set the player back until they successfully accomplish some goal. Quark's description that you can lose the battle shows that the holoprogram is interactive in a way that directly mimics modern video games, it's not just an immersive non-interactive movie.

A:

As Keen perhaps alluded to, The Game was more an episode about drug addiction than about video games.  DS9, TNG, and even Voyager have many holodeck episodes which are much more likely to be the future equivalent of video games than what we think of today.
A society like the Federation prizes personal self-betterment over personal hedonism.  So it's conceivable that video-game playing, like in our time, would be socially looked down upon, as we see with Barkley's holo-addiction.  To a society with the technology and the means to explore the limits of human understanding, game playing might simply seem childish or boring.  Also, why would people bother with controllers and pre-conceived notions of games, when one has access to a holodeck where one can literally live any game reality you or anyone else can dream of? (answer: because they are out-of-shape)
There are a few episodes, however, that elude to modern video games without the holodeck.  For instance,
Move Along Home in DS9 was about a virtual reality game that some of the players fear could kill them.  A matrix precursor of sorts.  It's like a more advanced version of Mario Party.

A:

Star Trek: TOS and The Motion Picture both indicate a number of games (some table-top, and some videogames) that are played in the 23rd century.
Star Trek: TNG and its successor series' have holo-decks, so I guess by this point CoD-like videogames would have been supplanted as you can really get in on the action in a holo-deck (as long as the safeties are properly engaged). There are still table-top games (like the 3d chess).
We also see a 2-player strategy videogame in TNG (s2e23 "Peak Performance").
The thing is - the audience probably wouldn't be interested in watching characters play videogames, so they wouldn't have been featured all that much.


Q:

mysqli Errors in Php

This code block from signinaction.php gave me a couple mysqli errors I didn't understand:
<?php
$u = $_POST["user"];
$p = md5($_POST["pass"]);
if($u == "" || $p == ""){
    header("Location: index.php");
    exit();
} else {
    $sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
    $query = mysqli_query($db_conx, $sql);
    $row = mysqli_fetch_row($query);
    $db_id = $row[0];
    $db_u = $row[1];
    $db_p = $row[2];
}
?>

The errors where:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given
  in /home/u776686576/public_html/signinaction.php on line 9 Warning:
  mysqli_fetch_row() expects parameter 1 to be mysqli_result, null given
  in /home/u776686576/public_html/signinaction.php on line 10

Please help me fix and understand them more, I have been looking around for a while and I can't seem to find any solutions.

A:

There is no connection. After you connect, add this:
if( mysqli_connect_errno() ) {
    throw new exception(mysqli_connect_error(), mysqli_connect_errno());
}

That will show you the error why it is not connecting.
To explain the error, 'null given' can be read as 'is not defined' (which is not 100% accurate, but here it is). Simply put, the variable which holds the connection is not set, which probally means it is not being defined. If you would have a bad connection the variable would be false.


Q:

Syntax error when creating mysql function

mysqlfile.sql:
DROP FUNCTION IF EXISTS func1;
DELIMITER //
CREATE FUNCTION func1(N INT) RETURNS INT
BEGIN
  RETURN (
      select * from Employee;
  );
END//
DELIMITER ;

executed source mysqlfile.sql, got an error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ';
  );
END' at line 4

How should I modify the code?

A:

A function returns 1 value, as far I can see you want to return a dataset.
You must create procedure in order to get what you need.
 DELIMITER //
 CREATE PROCEDURE getEmployees()
 BEGIN
  SELECT *  FROM employee;
 END //
 DELIMITER ;

You can call it by  call getEmployees();


Q:

Get a reference to a element nested inside a modal

I'm trying to get a reference to an element nested inside a modal. While using @ViewChild works for the modal, its not working for any nested elements. eg: the datePicker in the code below. Working demo here: https://stackblitz.com/edit/angular-s8dtmm-8gqgus (The 2nd console for datePicker is undefined)
export class AppComponent {
  @ViewChild('content') modal: ElementRef;
  @ViewChild('dp') datePicker: ElementRef;

  constructor(private modalService: NgbModal) {}

  open() {
    this.modalService.open(this.modal);
    console.log('modal', !!this.modal); // ref to #content
    console.log('dp', this.datePicker); // undefined
  }
}

Template:
<ng-template #content let-modal>
  <input ngbDatepicker #dp="ngbDatepicker">
  <button class="calendar" (click)="dp.toggle()">Date picker</button>
</ng-template>
<button(click)="open()">Open  modal</button>

A:

If you can modify your example so that the modal content is a separate component (i.e. based on this example rather than this one) then you should be able to access the datePicker component in the open() method. I have created a launch-modal.component which defines the "Open" button and logs out the value of dp when the modal is opened:
launch-modal.component.html
<button class="btn btn-outline-primary" (click)="open()">Open  modal</button>

launch-modal.component.ts
import { Component, ElementRef } from '@angular/core';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from './modal.component';

@Component({
  selector: 'launch-modal-component',
  templateUrl: './launch-modal.component.html'
})
export class LaunchModalComponent {
  constructor(private modalService: NgbModal) {}

  open() {
    const modalRef = this.modalService.open(ModalComponent);
    console.log('dp', modalRef.componentInstance.datePicker);
  }
}

I've then defined a modal.component.ts that defines the modal content (this is based  on the app.module.html in your question, and defines a ViewChild for the datePicker):
modal.component.ts
import { Component, ElementRef, ViewChild } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'modal-component',
  template: `
  <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
    ×
  </button>
  <input ngbDatepicker #dp="ngbDatepicker">
  <button class="btn btn-outline-primary calendar" (click)="dp.toggle()" type="button">Date picker</button>
  `
})
export class ModalComponent {

  @ViewChild('dp') datePicker: ElementRef;

  constructor(public activeModal: NgbActiveModal) {}
}

The output of the console when the modal is opened is:

Please see this Stackblitz for a working demo.


Q:

Why list comprehension is much faster than numpy for multiplying arrays?

Recently I answered to THIS question which wanted the multiplication of 2 lists,some user suggested the following way using numpy, alongside mine which I think is the proper way :
(a.T*b).T

Also I found that aray.resize() has a same performance like that. any way another answer suggested a solution using list comprehension :
[[m*n for n in second] for m, second in zip(b,a)]

But after the benchmark I saw that the list comprehension performs very faster than numpy :
from timeit import timeit

s1="""
a=[[2,3,5],[3,6,2],[1,3,2]]
b=[4,2,1]

[[m*n for n in second] for m, second in zip(b,a)]
"""
s2="""
a=np.array([[2,3,5],[3,6,2],[1,3,2]])
b=np.array([4,2,1])

(a.T*b).T
"""

print ' first: ' ,timeit(stmt=s1, number=1000000)
print 'second : ',timeit(stmt=s2, number=1000000,setup="import numpy as np")

result :
 first:  1.49778485298
second :  7.43547797203

As you can see numpy is approximately 5 time faster. but most surprising thing was that its faster without using transpose, and for following code :
a=np.array([[2,3,5],[3,6,2],[1,3,2]])
b=np.array([[4],[2],[1]])

a*b

The list comprehension still was 5 time faster.So besides of this point that list comprehensions performs in C here we used 2 nested loop and a zip function So what can be the reason? Is it because of operation * in numpy?
Also note that there is no problem with timeit here I putted the import part in setup.
I also tried it with larger arras, the difference gets lower but still doesn't make sense  :
s1="""
a=[[2,3,5],[3,6,2],[1,3,2]]*10000
b=[4,2,1]*10000

[[m*n for n in second] for m, second in zip(b,a)]
"""
s2="""
a=np.array([[2,3,5],[3,6,2],[1,3,2]]*10000)
b=np.array([4,2,1]*10000)

(a.T*b).T

"""

print ' first: ' ,timeit(stmt=s1, number=1000)
print 'second : ',timeit(stmt=s2, number=1000,setup="import numpy as np")

result :
 first:  10.7480301857
second :  13.1278889179

A:

Creation of numpy arrays is much slower than creation of lists:
In [153]: %timeit a = [[2,3,5],[3,6,2],[1,3,2]]
1000000 loops, best of 3: 308 ns per loop

In [154]: %timeit a = np.array([[2,3,5],[3,6,2],[1,3,2]])
100000 loops, best of 3: 2.27 µs per loop

There can also fixed costs incurred by NumPy function calls before the meat
of the calculation can be performed by a fast underlying C/Fortran function. This can include ensuring the inputs are NumPy arrays,
These setup/fixed costs are something to keep in mind before assuming NumPy
solutions are inherently faster than pure-Python solutions. NumPy shines when
you set up large arrays once and then perform many fast NumPy operations
on the arrays. It may fail to outperform pure Python if the arrays are small
because the setup cost can outweigh the benefit of offloading the calculations
to compiled C/Fortran functions. For small arrays there simply may not be enough
calculations to make it worth it.

If you increase the size of the arrays a bit, and move creation of the arrays
into the setup, then NumPy can be much faster than pure Python:
import numpy as np
from timeit import timeit

N, M = 300, 300

a = np.random.randint(100, size=(N,M))
b = np.random.randint(100, size=(N,))

a2 = a.tolist()
b2 = b.tolist()

s1="""
[[m*n for n in second] for m, second in zip(b2,a2)]
"""

s2 = """
(a.T*b).T
"""

s3 = """
a*b[:,None]
"""

assert np.allclose([[m*n for n in second] for m, second in zip(b2,a2)], (a.T*b).T)
assert np.allclose([[m*n for n in second] for m, second in zip(b2,a2)], a*b[:,None])

print 's1: {:.4f}'.format(
    timeit(stmt=s1, number=10**3, setup='from __main__ import a2,b2'))
print 's2: {:.4f}'.format(
    timeit(stmt=s2, number=10**3, setup='from __main__ import a,b'))
print 's3: {:.4f}'.format(
    timeit(stmt=s3, number=10**3, setup='from __main__ import a,b'))

yields
s1: 4.6990
s2: 0.1224
s3: 0.1234


Q:

cannot write strings to file using '.writeline' method of a streamwriter

I want to write a simple string in a text file using the stream writer class,But it doesn't seem to work(and there are no errors).here's my code:
StreamWriter test = new StreamWriter("mytext.txt", true);

// used the below code too to create the file. It didn't work either!
//StreamWriter test = File.CreateText("mytext.txt");
test.WriteLine("hello");

when I run this code,nothing will be added to the text file!Where did I go wrong?(ps:I used the full path file names too!but it didn't work!)

A:

using(StreamWriter test = new StreamWriter("mytext.txt", true)){
        test.WriteLine("hello");
}

problem is that the buffer of your stream is not flushed ... you could either call flush() or make sure it is properly disposed by the using block ...


Q:

How do I fetch translated strings?

I have a progressively decoupled Reactjs application running on top of Drupal. Its a multilingual application.
I need to fetch the translated strings from the Drupal itself and handle the translations editor and everything in Drupal itself, rather than maintaining a separate translation system for react.
How is it possible? A simple Drupal.t() doesn't work. I checked.
Any examples I can refer?

A:

Drupal.t() works in this case. Have to to compile the javascript and clear the Drupal cache in order for strings to appear.
For props way:
On get_sample_props():
function getsampleprops() {
  return ['sampleval' => t('Hello World!!!')];
}

On the controller,
$build = [
  '#theme' => 'sample_react',
  '#props' => json_encode($this->get_sample_props()),
];

On the template, I did:

On the React side, I used
$val = this.props.labels.sampleval;

Volia, its done. Its bit inconvenient, but work gets done.


Q:

Dynamically create variable name

In objective-c is there a way to dynamically create a variable name. Like I pass a string into a method and the method creates an NSString whos name is the string that was passed in. Something like
-(void)create:(NSString *)str{

NSString *[NSString stringWithFormat:@"%@", str];
}

Or maybe there is a way to change an already existing variables name.
NSString *password;
password.name = entryPassword;

A:

I'm sure that someone will point out some obscure exception, but in general, this is not possible in any compiled language.


Q:

Fail to pass array into function. Why isn't working?

I am a beginner in C Programming, and I need help on this.
There are no errors nor any warnings on this c code, but I can't seem to get the array to pass the values into the calcMagicNumber function. How do I fix this?
Thanks in advance!!
#include <stdio.h>

//function prototypes
void printHeader ();
void askForNumber();
int calcMagicNumber(int num[], int size );
void writeResults(char*, int, int);
void goodbye();

int main (){
    //assign the variables
    char name[51];                    //for user to input name
    char option='Y';                  //option for user to continue the program
    int magicNumber=0;                //to calculate the magic number
    int flag=0;      //to determine if the magic number is an even or odd number
    int num[5]={0,0,0,0,0};                 //for user to input the 5 numbers

    printHeader();

    puts("Please enter your name");
    scanf("%[^\n]s", name);

    do{

        //call the function calcMagicNumber to produce the magic number
        magicNumber = calcMagicNumber(num, 5);

        //determine if the magic number is an even number
        if(magicNumber%2==0){
            flag=1;
        }
        else{
            flag=0;
        }

        //call function writeResults to print out the user's name, the magic
number and whether the magic number is even
        writeResults(name, magicNumber, flag);

        fflush(stdin); //clear buffer

        //ask user if he or she would like to go again
        puts("Would you like to go again? [y/n]");
        scanf("%c", &option);

        option = toupper(option); //to convert the user's input into capital
letters

    }while(option == 'Y');

    goodbye();

    return 0;
}

//function bodies
void printHeader (){
    //print out name and chapter 3 - magic number
    printf("Chapter 3- Magic Number \n");
    printf("Tan Su Fern\n\n");
}

void askForNumber(){
    int i=1;
    int num[5]={0,0,0,0,0};

    //ask user to input number
    for(i=1;i<=5;i++){

        puts("Please enter a number.");
        scanf("%d", &num[i]);

    }
    num[i]=i;
    printf("\n%d, %d, %d, %d, %d", num[1], num[2], num[3], num[4], num[5]);
}

int calcMagicNumber(int num[], int size ){
    int magicNumber=0;

    //call askForNumber function for user to input 5 numbers
    askForNumber();

    printf("\n%d, %d, %d, %d, %d", num[1], num[2], num[3], num[4], num[5]);
    //calculate the magic number based on the numbers input by the user
    magicNumber = (num[1]*num[5])-(num[2]+num[3]+num[4]);

    return magicNumber;
}

void writeResults(char* name, int magicNumber, int flag){
    //print out the magic number and the user's name
    printf("\nHi %s , your magic number is %d.\n", name, magicNumber);

    //print out if the magic number is an even or odd number
    if(flag==1){
        printf("This is an even number.\n\n");
    }
    else{
        printf("This is an odd number.\n\n");
    }
}

void goodbye(){
    //say goodbye
    printf("goodbye");
}

A:

Problem is a second array within your function askForNumber
void askForNumber()
{
    int num[5] = { 0, 0, 0, 0, 0 };
    //  ^^
}

This second array co-exists to the one defined in main as long as you are within the function, but will be destroyed again as soon as you leave the function. The values of the user will be assigned to this second array, while the first one remains untouched.
Instead, you need to pass main's array (the one you passed to calcMagicNumber) further to askForNumber:
void askForNumber(int num[], size_t size)
{
    // int num[5] = { 0, 0, 0, 0, 0 };
    //     ^^ drop this one!
}

Side note: In C (this is different to C++), a function not accepting any parameters actually is declared/defined as:
void f(void);
//     ^^^^

Leaving out the void keyword makes it possible to pass arbitrary number of parameters to the function. Try this:
void good(void) { }
void bad() { }

int main()
{
    good();
    bad(1);
    bad(1, 2, 3);
    good(1); // <- this is the ONLY line that won't compile...
}

The void f() syntax is a remainder of pre-ANSI C times where function parameters where declared afterwards. Prefer not to use this syntax any more.


Q:

Why there are so many tags without any question related to them?

Why do these tags exist if they have no associated questions?
Tags: reinterviewing, self-employment, singapore, supplies, untagged, visa, workers-compensation, workplace-routine, phone, quitting, promises, outside-of-workplace, paperwork, multicultural, mexico, masters, library, it-departments, it-industry, inmigration, job-title, jury-duty, customer-relations, demotion, departments, germany, hardware, health, illness, hours, exercise, exit-interview, charity, cliches, assessment, alertness, banking, batna, accommodations, complaint, boss, bosses, headhunter, recruiters and reference.
In my opinion, some of the tags seem like duplicates (like bosses and boss), some seem off topic (like hardware, mexico, singapore, germany), some too specific (like batna) and finally, google told me that inmigration should be immigration.

A:

Let's categorize these tags so that it's easier to identify areas that might need action...
Tags with just 1 question:
Ideally, we should determine if these tags are needed. If they don't have any value, they can be removed and replaced with a better tag. But if the tag is something that could come up again or that could help people find this information, then the tag should remain.

reinterviewing
self-employment
singapore
supplies
visa
workers-compensation
workplace-routine
phone
quitting
promises
outside-of-workplace
paperwork
multicultural
mexico
masters
library
it-departments
it-industry
immigration (fixed spelling)
jury-duty
customer-relations
demotion
departments
germany
hardware
health
hours
exercise
exit-interview
charity
cliches
assessment
alertness
banking
batna  (Possibly meaning Best Alternative to a Negotiated Agreement )
accommodations
complaint

Tags that are synonyms of other tags:
These tags are synonyms of other tags. This means that the question can be tagged with either tag and still show up in the same tag search. For instance, searching for the tag "boss" or "bosses" shows me the same 122 results as if I searched for the "management" tag.
Tag synonyms are often used when different people try to use different tags that really identify the same groups of questions.

Boss and Bosses are a synonym of Management. 122 questions hold this tag.
job-title is a synonym of title. There are 13 questions with these tags.
illness and sickness are synonyms. There are 5 questions with these tags.
headhunter and recruiter are synonyms of recruitment. There are 58 questions with this tag.
reference is a synonym of references. There are 22 questions with this tag.

Untagged Questions:

"untagged" is a special tag that is used on questions that do not have a tag. Ideally, we should find tags that apply to these posts. Currently, there is only 1 question that has no tags.


Q:

Python split unicode

I have the following Unicode string:
{u'prices': [{u'ask': 1.05321, u'instrument': u'EUR_USD', u'bid': 1.05308, u'time': u'2016-12-30T02:53:26.928268Z'}]}

and would like to convert it to a Dataframe with this structure:
ask           1.05321
instrument    EUR_USD
bid           1.05308
time          2016-12-30T02:53:26.928268Z

thanks in advance.

A:

If you mean pandas data frame:
import pandas as pd

dd = {u'prices': [{u'ask': 1.05321, u'instrument': u'EUR_USD', u'bid': 1.05308, u'time': u'2016-12-30T02:53:26.928268Z'}]}

pd.Series(dd['prices'][0]).to_frame().reset_index()

#        index  0
#0         ask  1.05321
#1         bid  1.05308
#2  instrument  EUR_USD
#3        time  2016-12-30T02:53:26.928268Z

Or use json_normalize:
from pandas.io.json import json_normalize
json_normalize(dd['prices']).T.reset_index()

#        index        0
#0         ask  1.05321
#1         bid  1.05308
#2  instrument  EUR_USD
#3        time  2016-12-30T02:53:26.928268Z


Q:

Error going full screen flash applet (NPObject)

I've googled about for an hour or so now and can't find a solution which works, I have a flash player and I need to full screen it using JavaScript, I can get the JavaScript to send commands (my volume function works) but my full screen one always returns:
Error: Error calling method on NPObject.

Most posts referring to this are solved with adding the as3 security line, for me, that's not the problem
Security.allowDomain("mydomain.com");
function fScreen() {
    if (stage.displayState== "normal") {
        stage.displayState="fullScreen";
        stage.scaleMode = StageScaleMode.NO_SCALE;
    } else {
        stage.displayState="normal";
    }
    call('console.log', 'okok');
}

When I just output to the console it goes through fine. Any other ways of going fullscreen?
Thanks

A:

Have you added alloweFullScreen in the embed and object tags?
To use full-screen mode, you need to add a new parameter to the  and  tags in your HTML. Here is an example of the  and  tags with full screen enabled:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,18,0" width="600" height="400" id="fullscreen" align="middle">
<param name="allowFullScreen" value="true" />
<param name="movie" value="fullscreen.swf" />
<param name="bgcolor" value="#333333" />
<embed src="fullscreen.swf" allowFullScreen="true" bgcolor="#333333" width="600" height="400" name="fullscreen" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
 </object>

Check out this article: http://www.adobe.com/devnet/flashplayer/articles/full_screen_mode.html