Домой Блог Страница 84058

Getting Started with R Using Java — Developer.com

0

NewsHubR is one of the most commonly used software packages for statistical computing and graphics and Java is the most commonly used programming language. rJava is a JNI (Java Native Interface)-based, R-to-Java interface with which Java objects may be created and Java methods called and Java fields accessed from R. In this tutorial, we shall get started with using the rJava R package to use Java from R. This tutorial has the following sections:
R is supported on Unix-like OS, Windows OS, and Mac OS X. Support for Mac OS Class was discontinued with R 1.7.1. We have used R on Windows OS for which you can download the binaries file.
Double-click the binaries file to install R on Windows (see Figure 1). After R has been installed, start R to log in to the R Console.
Figure 1: Installing R
Output the R version with the following command:
The R version 3.3.1 is used in his tutorial.
Create a simple R function to test R. The following hello function takes an arg for its name and outputs a hello message.
Invoke the R function with a name String.
A message gets output:
The hello function and its output is shown in R Console (see Figure 2).
Figure 2: The hello function and its output
To install the rJava package, run the following command:
The rJava package gets installed, as shown in Figure 3.
Figure 3: A successful installation
Before you are able to use any rJava functions, we need to initialize the JVM. The usage of.jinit is shown, as follows.
The classpath arg prepends additional classes to the CLASSPATH setting. The parameters arg specifies the parameters with which the virtual machine is to be invoked. The «… » indicates other implementation specific to Java initialization parameters.
The «silent» attribute is set to FALSE by default, indicating that no warnings are issued. Setting «force.init» to TRUE would re-initialize the JVM if it is running. The.jinit returns 0 if the JVM got initialized and a -ve integer if it did not. A +ve integer is returned if the JVM got initialized partially. Before initializing the JVM, the rJava library must be loaded.
The preceding function calls are shown in R Console (see Figure 4).
Figure 4: Result of the preceding function calls
Before importing any Java packages, the JVM must be initialized or an error gets generated.
The following is an example of providing parameters to set the maximum Java heap size with — Xmx .
In this section, we discuss how a classpath may be found or set. To list the entries in classpath, use the.jclassPath() function.
An output such as the following lists the directories and jars in the classpath.
To add directories and jars to the classpath, use the .jaddClassPath(path) function. For example, add the C:\\ojdbc6.jar jar to the classpath.
Subsequently, if the classpath entries are output, the C:\\ojdbc6.jar also should get listed.
The .jnew function creates a new Java object. It has the following usage:
The class arg specifies the class name for which a new object is to be created, and the subsequent «… » indicates the args to be passed to the class constructor. The check=TRUE arg invokes the.jcheck function before and after invoking the class constructor to clear any Java exceptions. The silent arg indicates if errors if any are to be output and, if set to FALSE , if creating an object generates an error the error is output and the object creation fails. Otherwise, a null reference is returned if creating an object fails due to an error. It is meaningful to set only silent=!check because, if exceptions are not being checked with a check=FALSE setting, they cannot be output, even with a silent=FALSE setting.
As an example, create a new String object initialized with a «Hello World! » String. Subsequently, output the String object.
The Java object created is output.
A sequence of commands loading the rJava library, initializing the JVM, creating a String object, and outputting the String object and the output is shown in the R Console (see Figure 5).
Figure 5: Creating and outputting a String object
The .jcall function is used to call a Java method. With only the required function parameters, the usage is as follows.
As an example, using the object reference «s» returned in the previous section, invoke the .jcall method to call the «length» method of the String object and return an int .
A value of 12 is returned, which is the length of the «Hello World! » String.
An alternative short form to invoke the length method using the object reference «s» is with objectRef$method() notation. For example, the preceding method call also could be made as follows, outputting 12.
The .jstrVal function could be used to call the toString() method of a String object to output the String value. For example, to output the String value of the same String object «s», invoke the.jstrVal method as follows:
The String reference value should get output.
The output from preceding function calls is shown in R Console, as shown in Figure 6.
Figure 6: Output from the «Hello World! » function call
A Java method also may be called using J, which is a high-level API for accessing Java. J creates a Java class reference or calls a Java method and has the following usage:
Only the «class» arg is required and is the Java object reference or the fully qualified class name specified in JNI notation, such as java/lang/String or Java notation, such as java.lang. String. As an example, call the parseDouble method in Java class java.lang. Double with method arg «10.2».
The method call should return the double value.
To invoke a static method, also called a class method, the $ operator could be used on the Java class reference. As an example, call the static method parseDouble(String s) in the java.lang. Double class as follows, with the arg supplied to the parseDouble method as «10.2».
An output of double value 10.2 is returned.
The output from the preceding method calls in R Console is as follows (see Figure 7).
Figure 7: Returning «10.2»
In the next article, we shall explore using Strings further. We also shall discuss creating a Java Swing application in R. Another feature discussed in the next article is finding whether an object is an instance of a class.

© Source: http://www.developer.com/java/ent/getting-started-with-r-using-java.html
All rights are reserved and belongs to a source media.

У Держдепі і Мін'юсті США виступили проти міграційної політики Трампа

0

NewsHubДональд Трамп
Reuters
Група співробітників Держдепартаменту США склала лист, в якому висловлюється незгода з міграційною політикою президента Дональда Трампа, повідомляє Російська служба BBC.
У петиції, підтримуваної сотнями дипломатів, йдеться, що міграційний указ Трампа не захистить країну від терористичних атак, а, навпаки, налаштує іноземців проти американських громадян.
Новини за темою: Прокурор штату Вашингтон судитиметься з Трампом через указ про мігрантів
Дипломати зазначають, що прийнятий Трампом тимчасову заборону на в’їзд громадян семи переважно мусульманських країн — це спроба не пустити в країну невелику кількість потенційних злочинців, заборонивши при цьому в’їзд 200 млн законослухняних громадян.
Як повідомляють американські ЗМІ, журналісти вже бачили кілька варіантів листи — судячи з усього, остаточний варіант ще не готовий.
Проте Білий дім вже прокоментував петицію. Прес-секретар адміністрації Трампа Шон Спайсер заявив, що незгідні мають або змиритися, або йти.
Новини за темою: Адміністрація Трампа розробила проект указу про обмеження видачі робочих віз
За словами Спайсер, Трамп хоче захистити Америку, а дипломати перебільшують негативний ефект від міграційного указу президента.
Листи, в яких дипломати заявляють про свій протест проти політики керівництва, зазвичай відправляються так званим «каналом незгоди».
Цей канал з’явився під час В’єтнамської війни, він традиційно використовується дипломатами для вираження невдоволення рішеннями, прийнятими у зовнішній політиці. Підписувати лист можна анонімно.
Звернення дипломатів, швидше за все, буде передано Томасу Шеннону, який виконує обов’язки держсекретаря, поки не схвалена кандидатура Рекса Тіллерсона, висунутого Трампом на посаду глави зовнішньополітичного відомства.
Виконуюча обов’язки генерального прокурора США Саллі Єйтс заявила, що міністерство юстиції не буде захищати міграційний указ президента Дональда Трампа в суді.
Саллі Єйтс, призначена на свою посаду при Обамі, зазначила, що «не переконана у законності указу президента».
«Міністерство юстиції не буде представляти аргументи в захист розпорядження президента», — заявила вона.
На посаді генпрокурора Єйтс має змінити висунутий Дональдом Трампом Джефф Сессіонс.
Трамп підписав міграційний указ 27 січня. Розпорядження Трампа передбачає припинення прийому сирійських біженців в США на невизначений термін. Інші програми прийому біженців припинені на 120 днів. Громадянам семи мусульманських країн — Ірану, Іраку, Лівії, Сомалі, Судану, Сирії та Ємену — заборонений в’їзд в США на 90 днів.
Про готовність оскаржити указ президента США заявили прокурори ряду регіонів, у тому числі прокурор штату Вашингтон Боб Фергюсон.

Similarity rank: 11

© Source: http://ua.112.ua/svit/u-derzhdepi-i-miniusti-ssha-vystupyly-proty-mihratsiinoi-polityky-trampa-368633.html
All rights are reserved and belongs to a source media.

Arbeitslosenzahl steigt im Januar auf 2,777 Millionen

0

NewsHubNürnberg (dpa) — Die Zahl der Arbeitslosen in Deutschland ist im Januar um 209 000 auf 2,777 Millionen gestiegen.
Das sind 143 000 Erwerbslose weniger als vor einem Jahr, wie die Bundesagentur für Arbeit in Nürnberg mitteilte. Die Arbeitslosenquote stieg um 0,5 Punkte auf 6,3 Prozent.

Similarity rank: 1.1

© Source: http://www.sueddeutsche.de/news/karriere/arbeitsmarkt-arbeitslosenzahl-steigt-im-januar-auf-2777-millionen-dpa.urn-newsml-dpa-com-20090101-170131-99-97939?source=rss
All rights are reserved and belongs to a source media.

Бывший глава банка Михайловский сбежал из-под ареста

0

NewsHubСуд постановил задержать сбежавшего из-под домашнего ареста бывшего руководителя банка «Михайловский» Игоря Дорошенко. Об этом сообщила пресс-служба столичной прокуратуры, 30 января.
Дорошенко должен был прийти в прокуратуру для объявления ему нового подозрения в доведении банка до банкротства в пятницу, 27 января, но не пришел. Адвокат заявил, что его подзащитный болен.
— Проверкой информации о болезни И. Дорошенко, которая была предоставлена его адвокатом, получены документальные подтверждения о отсутствие оснований для его госпитализации. В настоящее время органами прокуратуры и СБУ принимаются меры для установления местонахождения подозреваемого и исполнение решения суда о его задержании, — сказано в сообщении.
Дорошенко инкриминируют две статьи уголовного кодекса — хищения в особо крупных размерах и доведения банка до банкротства. 13 августа Шевченковский райсуд Киева арестовал банкира на два месяца с правом внесения 137 миллионов гривен залога. 5 декабря суд освободил из-под стражи Дорошенко и отправил его под домашний арест.
ЧИТАЙТЕ ТАКЖЕ
За счет кого решили проблему «Михайловского»
НБУ ввел временную администрацию в банк «Михайловский» 23 мая 2016 года. После признания банка неплатежеспособным оказалось, что часть денег вкладчиков под высокие проценты привлекали некие финансовые компании (они не являются участниками ФГВФЛ, следовательно потерянные средства фондом не возмещаются), а сам «Михайловский» выступал лишь посредником.

Similarity rank: 9

© Source: http://kp.ua/incidents/565475/
All rights are reserved and belongs to a source media.

В зоне АТО за сутки пострадали 20 военных

0

NewsHubВ результате артиллерийских обстрелов в зоне АТО за сути пострадали 20 военных, из которых трое погибли. Об этом сообщили в пресс-службе штаба АТО , 30 января.
Военных обстреливали из крупнокалиберных орудий, которые запрещены минскими соглашениями. В ход шли 122-миллиметровые и 152-миллиметровые пушки, крупнокалиберные минометы, стрелковое оружие. Всего по всем направлениям зафиксирован 37 обстрелов за сутки.
— Из этого оружия многократно обстреливали Авдеевку, Новотроицкое Луганское, Невельске и Опытное, — сказано в сообщении, — В то же время по Песках и Авдеевке течение дня огонь вели танки. Кроме того, на Мариупольском направлении с 152 миллиметровой артиллерии боевики вели огонь по Водяное. С минометов обстреливали Красногоровку и Лебединский. С гранатометов и стрелкового оружия — Павлополь, Талаковка, Гнутово, Широкино и Водяное, — сказано в сообщении.
Министр обороны Степан Полторак ранее заявил, что под Авдеевкой ВСУ 29 января захватили опорный пункт «ДНР».
30 января в Авдеевку направили дополнительный отряд полиции для усиления местного гарнизона правоохранителей.
29 января утром силы «ДНР» начали штурм позиций украинских военных в районе Авдеевской промзоны. В «ДНР» традиционно в обстрелах обвинили ВСУ. Там заявили, что украинские бойцы «атаковали их позиции в районе промзоны под Ясиноватой.
Также ранее сообщалось, что в боях возле Авдеевки на прошлых выходных погибли четыре бойца ВСУ. Это 23-летний капитан Андрей Кизило, 25-летний младший сержант Владимир Больченко, 28-летний солдат Дмитрий Оверченко и 34-летний сержант Владимир Крижанский.
ЧИТАЙТЕ ТАКЖЕ
«Донецкий треугольник»: борьба за «серую зону» или крест на Минске?
После боя, который длился почти сутки, минские договоренности кажутся не актуальными. Так ли это разбиралась «КП в Украине».

Similarity rank: 10.6

© Source: http://kp.ua/incidents/565451/
All rights are reserved and belongs to a source media.

Japan's central bank keeps policy intact, upgrades outlook

0

NewsHubJapan’s central bank wrapped up its first board meeting of the year on Tuesday with a decision to keep its ultra-loose monetary policy unchanged, though it upgraded its growth forecasts for the world’s third-largest economy.
The Bank of Japan cited easy lending conditions, rising exports and stronger government and corporate spending, in part linked to the 2020 Tokyo Olympics, as reasons to expect a more robust recovery, despite recent weakness in consumption and investment.
It forecast the economy will grow at a 1.4 percent annual pace in the current fiscal year, which ends March 31, up from an earlier estimate of 1.0 percent. It expects 1.5 percent growth in the coming fiscal year, up from the earlier 1.3 percent forecast.
The government reported Tuesday that industrial output rose in December, helped by strength in manufacturing of passenger cars and auto parts, though the 0.5 percent month-on-month increase was slower November’s 1.5 percent expansion.
Part of that improvement is due to a weakening in the Japanese yen against the dollar since the Nov. 8 U. S. presidential election, which has raised uncertainty over the future direction of U. S. policies.
The BOJ cited that as one of several risks beyond Japan’s control. Others include Britain’s plan to leave the European Union, China’s economy and other «geopolitical risks. »
Under BOJ Gov. Haruhiko Kuroda, the central bank is pumping tens of billions of dollars a year into the economy through purchases of government bonds and other assets. It also has made the benchmark interest rate minus 0.1 percent, to discourage banks from keeping money idle. The aim is to counter deflation and keep credit cheap, encouraging banks to lend and businesses to borrow more.
That formula, dubbed «Abenomics» for Prime Minister Shinzo Abe, has yielded mixed results. Growth has remained below expectations and inflation stuck near zero, stymieing efforts to «reflate» the economy and compel consumers and businesses to step up purchases to avoid future price hikes.
Data for December showed an uptick in manufacturing output, which rose 0.5 percent from the month before but was a slower increase than the 1.5 percent month-on-month increase in November.
Household spending fell 1.5 percent from the year before in December, and 2.1 percent from the previous month, despite a 2.3 percent increase in average real income, which partly resulted from bonuses traditionally paid twice a year in Japan.
«The continued weakness of household spending and consumption in general is puzzling,» Masamichi Adachi of JPMorgan in Tokyo said in a research note. «However, we might have understated drags to consumption; concerns of senior people who have no labor income. »
He noted that spending in households of those over age 60 fell in December, which spending of younger households rose slightly.
The aging and shrinking of Japan’s population is countering efforts by the central bank and government to rekindle demand and sustain stronger levels of growth, said Bill Adams, an economist with The PNC Financial Services Group.
Even though Japanese businesses are increasingly short-handed — some fast-food outlets and convenience stores have stopped operating round-the-clock due to a lack of staff — wages are just not rising, and families tend not to spend more than they have to.
Japan’s unemployment rate remained steady at 3.1 percent in December, and averaged that level for all of 2016, the lowest in 22 years. The number of jobs available to job seekers rose to 1.43, the highest level since 1991.
«Japan’s shrinking labor market means that even with real GDP growth of barely more than 1.0 percent, its economy is growing above potential, tightening the labor market,» he said. But «Offsetting a labor market that is cyclically hot and getting hotter is Japan’s incredibly weak demographic makeup. «

Similarity rank: 1.1
Sentiment rank: 2.7

© Source: http://www.charlotteobserver.com/news/business/national-business/article129735179.html
All rights are reserved and belongs to a source media.

Реал предложил Бензема английским клубам

0

NewsHubПо информации Diario Gol, мадридский клуб сам обратился к Челси и Арсеналу и предложил им совершить трансфер Бензема. Не исключается и возвращение игрока во Францию, где его хочет видеть ПСЖ.
Уход Бензема может означать приход другого форварда в команду. В первую очередь, речь идет о Пьере-Эмерике Обамеянге, который сам заинтересован в переходе в Реал.
В текущем сезоне Бензема попал под критику из-за плохой формы и низкой реализации опасных моментов. В 27 матчах нападающий забил 8 голов.

© Source: http://korrespondent.net/sport/football/3808204-real-predlozhyl-benzema-anhlyiskym-klubam
All rights are reserved and belongs to a source media.

Обама поддержал протесты против скандального указа Трампа

0

NewsHub44-й президент США Барак Обама поддержал массовые протесты против скандального антимиграционного указала президента Дональда Трампа. Об этом сообщает издание Time.
Обама поблагодарил американцев за то, что они высказывают свой протест и заявил, что «в корне не согласен с дискриминацией в отношении лиц по причине их веры или религии».
Экс-президент сообщил, что воодушевлен уровнем взаимодействия, который происходит между американцами по всей стране.
«Граждане, реализуют свое конституционное право собираться, организовываться и заставлять слышать их голоса избранных чиновников — это именно то, чего мы ожидаем, когда американские ценности находятся под угрозой», — сказал он.
28 января Трамп подписал указ, которым ограничил иммиграцию беженцев из мусульманских стран.
Этот указ уже раскритиковали канцлер Германии Ангела Меркель , премьер-министр Канады Джастин Трюдо , премьер Великобритании Тереза Мэй и другие мировые лидеры и политики.
В администрации Трампа вчера заявили , что администрация Обамы еще во время своего правления приняла решение о необходимости дальнейшего ограничения на въезд мигрантов в Штаты.
Ранее сегодня сообщалось , что Европейская комиссия изучает законность указа президента США Дональда Трампа о запрете въезда в страну гражданам семи мусульманских государств.
Подписывайтесь на аккаунт ЛІГА.net в Twitter , Facebook , ВКонтакте и Одноклассниках : в одной ленте — все, что стоит знать о политике, экономике, бизнесе и финансах.

Similarity rank: 14

© Source: http://news.liga.net/news/world/14681501-obama_podderzhal_protesty_protiv_skandalnogo_ukaza_trampa.htm
All rights are reserved and belongs to a source media.

Полузащитник "Барселоны" Б забил потрясающий гол со штрафного (Видео)

0

NewsHub«Барселона» Б провела матч 23-го тура Сегунды Б против » Алькояно » (1:1).
Молодежка «Барселоны» смогла спастись от поражения и свела матч вничью благодаря шикарному голу со штрафного от Жерара Гумбау на 86-й минуте.
Благодаря ничьей «Барселона» Б сохранила лидерство в турнирной таблице и опережает «Алькояно» на 2 очка.

© Source: http://telegraf.com.ua/sport-cat/futbol/3129267-poluzashhitnik-barselonyi-b-zabil-potryasayushhiy-gol-so-shtrafnogo-video.html
All rights are reserved and belongs to a source media.

Ex-national security officials in both parties protest Trump order

0

NewsHub(CNN) A group of more than 100 former national security heavyweights from both political parties protested President Donald Trump’s executive order on refugees in a letter Monday, calling on the heads of three US government agencies to use their own power to ease some of the restrictions.

Similarity rank: 20
Sentiment rank: 1.4

© Source: http://rss.cnn.com/~r/rss/cnn_latest/~3/-V5zz0QVtf0/index.html
All rights are reserved and belongs to a source media.

Timeline words data