text:
Q: Form Values to same page This is my first post here so i wish to say thank you in advance :).
I have searched the web looking for a solution and thought this would be the best place.
I am trying to make a page where by when a user enters some form details it will post to the right section, i have achieved this by using javascript but am looking for away to do this server side as do not want the javascript seen on the client side.
I will have a template page with a form that will be used on all pages, the only thing that changes is the right side, i will then use an admin panel to add templates such as lets say emails in (html code) that will appear on the right side of the form, when the user enters all their info, on the form click will be placed into the code on the right.

<input type="text" class="form-control" id="name" placeholder="customer name">
<button type="button" onclick='changeThis()' class="btn btn-primary btn-lg btn-block"> Generate Code</button>

--------------------------------------------------------------------------

Dear

Dear
<?php echo $_POST['title']; ?>

A: <?php

if(isset($_REQUEST['first_name'])){
    $first_name= $_REQUEST['first_name'];
    $last_name= $_REQUEST['last_name'];
    $city= $_REQUEST['city'];
}

?>

Body

 //left div
  <form method="post">
    <input type="text" name="first_name">
    <input type="text" name="last_name">
    <input type="text" name="city">
    <input type="submit">
  </form>

 //right div

<?php echo $first_name;?>

<?php echo $last_name;?>

<?php echo $city;?>

A: After submitting the form you get the form values by $_POST. Now you can print the form values right side of the page. see the below code example.
//Form
<form action="">
<input type="text" name="title"/>
<input type="text" name="body"/>
<input type="submit" value="Submit"/>
</form>

//It is the right side of the page where form values need to print.
<?php
if(!empty($_POST)){  //if form submit then this code will execute
?>

<?php echo $_POST['title']; ?>

<?php echo $_POST['body']; ?>

<?php
}
?>


text:
Q: How to predefine and hide a column in SharePoint NewForm and EditForm? does anyone know how to predefine a column and hide it in SharePoint? I want to create a second NewForm for an already existing List. A new column with two options will make sure to differentiate the two entries in reports/views.
Example:
I have a list with two columns: Name (text) and Type (choice). I want to make two custom NewForms. Both will only have one editable field and both will have one hidden predefined field.
NewForm number 1 will have the Name column visible and Type selected as Male and hidden.
NewForm number 2 will have the Name column visible and Type selected as Female and hidden.
Is this possible?
Regards,
David

A: This is how I implemented this :)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('select[title=ColumnName]').val('ValueYouWant');
$("nobr:contains('ColumnName')").parent('h3').parent('td').parent('tr').hide();
});
</script>

A: It certainly is possible to modify the forms while the user is using them:
You can put the page into edit mode and add a Content Editor Web Part and fill it with javascript to do what you want. Or you can do the same using SharePoint Designer.
As for having more than one NewForm for a single list I don't know.

A: You can create a new custom NewForm.aspx page by right clicking on the existing page in SharePoint Designer and choosing "New from Existing Page."

As Dan mentioned, you can add JavaScript to your page to hide or default values. An option for you would be to use SPUtility.js (full disclosure.. a JavaScript library I maintain):
SPUtility.GetSPField('Gender').SetValue('Male').Hide();

A: Call the below function and specify Field Name:
function HideField(FieldName)
{
$('nobr:contains("'+FieldName+'")').closest('tr').hide();
$('td.ms-formlabel:contains("'+FieldName+'")').parent().hide();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: New-SPServiceApplicationPool does not create IIS application pool I have a weird problem on two different environments and I can't figure out what is wrong.
When I run this command New-SPServiceApplicationPool new_pool -Account domain\spservice it throws no errors, but new application pool in IIS does not appear.
If I run Get-SPServiceApplicationPool it lists this application pool, but it's still not visible in IIS.
I have also noticed that when I create new Service Applications like Managed Metadata and Secure store service - New WCF endpoints do not appear in "SharePoint Web Services" IIS Site.
Something is seriously wrong, but I don't understand what. Something prevents SharePoint from creating IIS artifacts.
ULS and Windows Event logs have no information about this problem at all. Except, for maybe SPEndpointAddressNotFoundException: There are no addresses available for this application.. But this is useless, because I know that IIS is missing the endpoints/and application pools, but there is no explanation as to why this is happening.
I wold greatly appreciate any help.
Update:
I've just tested how it is supposed to work with SharePoint 2013. When I run New-SPServiceApplicationPool, it only creates a new pool and a WCF endpoint inside 'SharePoint Web Services' IIS website when service on server is activated. There is no "Start" and "Stop" button in SP2016, but It says "started" against "Managed Metadata Service". Maybe I can stop and start it with PowerShell somehow and see if it helps...
Update #2
I've actually found "start" and "stop" buttons in SP2016. They are moved to System Settings--> Manage services on server. Turns out, that Managed Metadata and Secure store services were actually stopped... Even thougn it said "started" in the Central Admin home --> "Manage services in this farm". After I've started the services all missing Pools and endpoints in IIS were created within a few seconds

A: Turns out, that Managed Metadata and Secure store services were actually stopped... Even thougn it said "started" in the Central Admin home --> "Manage services in this farm". After I've started the services all missing Pools and endpoints in IIS were created within a few seconds


text:
Q: R igraph: label vertex by condition I have a graph g with a set of vertices and a list with the names of some "special" vertices.
I want the graph to display a label with the vertex name ONLY for these special vertices.
I tried something like this:
plot(g, vertex.size = 4, vertex.label = ifelse(V(g) %in% usernames, V(g)$label, ""), asp = F)

But apparently I'm missing something, because the predicate never enter TRUE.
Also, it seems like V(g)$label results in the following error:

Error in ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok] : replacement has length zero

Your help will be appreciated! :)

A: Turn V(g) into V(g)$label?
set.seed(1)
library(igraph)
g <- ba.game(26)
V(g)$label <- letters[1:26]
usernames <- sample(letters, 5)
plot(g, vertex.label = ifelse(V(g)$label %in% usernames, V(g)$label, NA))

or
set.seed(1)
library(igraph)
g <- ba.game(26)
usernames <- sample(vcount(g), 5)
plot(g, vertex.label = ifelse(V(g) %in% usernames, V(g), NA))

?


text:
Q: react-native run-android build failed Could not find com.google.android.gms:play-services-measurement-api:9.8.0 Trying to build my react native project after adding React-native-firebase to the application is causing it to fail to build the application. I am getting the following error:
* What went wrong:
Could not resolve all files for configuration ':app:debugCompileClasspath'.
> Could not find com.google.android.gms:play-services-measurement-api:9.8.0.
  Searched in the following locations:
      file:/Users/cliffc/Library/Android/sdk/extras/m2repository/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      file:/Users/cliffc/Library/Android/sdk/extras/m2repository/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
      file:/Users/cliffc/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      file:/Users/cliffc/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
      file:/Users/cliffc/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      file:/Users/cliffc/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
      file:/Users/cliffc/.m2/repository/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      file:/Users/cliffc/.m2/repository/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
      https://repo.maven.apache.org/maven2/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      https://repo.maven.apache.org/maven2/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
      https://jcenter.bintray.com/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      https://jcenter.bintray.com/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
      file:/Users/cliffc/projects/prod/commconn/cc/node_modules/react-native/android/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      file:/Users/cliffc/projects/prod/commconn/cc/node_modules/react-native/android/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
      https://dl.google.com/dl/android/maven2/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      https://dl.google.com/dl/android/maven2/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
      https://maven.google.com/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      https://maven.google.com/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
      https://jitpack.io/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.pom
      https://jitpack.io/com/google/android/gms/play-services-measurement-api/9.8.0/play-services-measurement-api-9.8.0.aar
  Required by:
      project :app > com.google.firebase:firebase-core:16.0.3 > com.google.firebase:firebase-measurement-connector-impl:17.0.1
      project :app > com.google.android.gms:play-services:9.8.0 > com.google.firebase:firebase-analytics:16.0.3

this is only one of them I get the same error for the following services:
Could not find com.google.android.gms:play-services-measurement-base:9.8.0.
Could not find com.google.android.gms:play-services-stats:9.8.0.
Could not find com.google.android.gms:play-services-ads-identifier:9.8.0.

My MainApplication get packages are:
protected List<ReactPackage> getPackages() {
    // Add additional packages you require here
    // No need to add RnnPackage and MainReactPackage
    mCallbackManager = new CallbackManager.Factory().create();
    return Arrays.<ReactPackage>asList(new MapsPackage(), new RNDeviceInfo(), new FBSDKPackage(mCallbackManager),
        new PickerPackage(), new RNFetchBlobPackage(), new VectorIconsPackage(),
        new ReactNativePushNotificationPackage(), new RNFirebasePackage());
    // eg. new VectorIconsPackage()
  }

Build.gradle (app):
ext {
    compileSdkVersion   = 27
    targetSdkVersion    = 27
    buildToolsVersion   = "27.0.1"
    supportLibVersion   = "26.1.0"
    googlePlayServicesVersion = "15.0.1"
    androidMapsUtilsVersion = "0.5+"
    firebaseVersion = "+"
}

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"

    defaultConfig {
        applicationId "com.commonconnectapp"
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 22
        versionName "1.0.1"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }

    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        if (details.getRequested().getGroup() == 'com.google.android.gms') {
            details.useVersion('9.8.0')
        }
    }
}

dependencies {
    compile project(':react-native-firebase')
   compile project(':react-native-push-notification')
    compile project(':react-native-maps')
    compile project(':react-native-image-picker')
    compile project(':react-native-fbsdk')
    compile project(':rn-fetch-blob')
    compile project(':react-native-vector-icons')
    compile project(':react-native-image-crop-picker')
    compile project(':react-native-device-info')
    compile fileTree(dir: "libs", include: ["*.jar"])
    implementation 'com.android.support:appcompat-v7:27.0.2'
    implementation 'com.android.support:design:27.1.0'
    implementation 'com.android.support:multidex:1.0.3'
    // compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    implementation project(':react-native-maps')
    compile project(':react-native-navigation')
    implementation 'com.facebook.android:facebook-android-sdk:4.34.0'
    implementation project(':react-native-fbsdk')
    implementation project(':react-native-firebase')
    implementation "com.google.firebase:firebase-core:16.0.3"
    compile "com.google.android.gms:play-services:15.0.1"
}

thank you in advanced for any help. If any more info is needed please let me know. I've been searching and tried some fixes to no avail. I'll keep researching and add the answer myself if I find it.

A: Something like that happened to me before. When you are installing native dependencies like that, in android studio you'll see different projects besides your main react native application.
One of these projects should be react native firebase if you installed it propertly.
Well, thia project, same as your main application project, has also a gradle file with dependencies.
Check if there the library the error specifies is there and it's the same version as your gms services in your main application.


text:
Q: How to send message from backend(java) to frontend(react) Hi Im still learning how to use react and java. I am creating a project where the front end is in react and the backend is in java.
I was wondering if someone would be able to point me in the right direction or give me an example of java sending a message to the front end in react. What Im essentially trying to do is give the user a message after the backend receives a file they submit. I already have the part where the backend is processing the file.
Ive tried looking at a lot of sites but theres not a lot of documentation out there for react and java as the backend.
thank you

A: What you need is Websocket, he provide a full-duplex communication channels over a single TCP connection. So, when you start a comunication between client and server, a session is created, making possible to send and receive message for both side.
Some possibilities are, use javax:

*

*https://docs.oracle.com/javaee/7/api/javax/websocket/package-summary.html

*https://www.baeldung.com/java-websockets
Use spring-websocket(if are you already using spring, will be easy to use):

*

*https://spring.io/guides/gs/messaging-stomp-websocket/

*https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/websocket.html
Here is another example with javax https://www.pegaxchange.com/2018/01/28/websocket-server-java/
So, there are a lot of examples.

A: Websocket would open a channel between the client and the server, so you can send a server message at any time.
But, if you are already using a POST from the client to upload the file, you could just send a response to the POST.


text:
Q: RT audio Mac error g++ compiling error Having problems getting rt audio to compile using simple application
#include "RtAudio.h"

int main()
{
        RtAudio *audio = 0;
        audio = new RtAudio;
        delete audio;
return 0;
}

to compile
g++ -Wall -D__MACOSX_CORE__ -o probe rtaudio.cpp RtAudio.cpp -framework CoreAudio -lpthread

error
Undefined symbols for architecture x86_64:
  "RtAudio::RtAudio(RtAudio::Api)", referenced from:
      _main in rtaudio-e456a2.o
      _main in RtAudio-a64f56.o
"RtAudio::~RtAudio()", referenced from:
  _main in rtaudio-e456a2.o
  _main in RtAudio-a64f56.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

A: You need to link your code with RtAudio library, so add -lrtAudio to your compile command:
g++ -Wall -D__MACOSX_CORE__ -o probe RtAudio.cpp -framework CoreAudio -lpthread -lrtAudio

And you have included two RtAudio, one "rtaudio.cpp" and two RtAudio.cpp, you should clear rtaudio.cpp, because you included #include "RtAudio.h" with uppercase in your main


text:
Q: ReSharper intellisense autoselect first option Basically, I want ReSharper's intellisense to work a lot like IntelliJ's, where all I have to do is press enter. I hate having to press down when selecting a option that's the first on the list and pressing enter, its slower than actually typing it out.

A: See this
This is really what I needed but in a different question, more of like a switcherooni :\ really wish this was pointed out better..


text:
Q: Парсинг .txt файла Здрастите.
Мне нужно найти в текстовом файле слово. Пример:
абажурчик   сущ неод ед муж им  125724
абажурчика  сущ неод ед муж род 219588
абажурчику  сущ неод ед муж дат 219589
абажурчик   сущ неод ед муж вин 219590
абажурчиком сущ неод ед муж тв  219591
абажурчике  сущ неод ед муж пр  219592
абажурчики  сущ неод мн им  1261349
абажурчиков сущ неод мн род 1261350
абажурчикам сущ неод мн дат 1261351
абажурчики  сущ неод мн вин 1261352
абажурчиками    сущ неод мн тв  1261353
абажурчиках сущ неод мн пр  1261354

абаз    сущ неод ед муж им  125725
абаза   сущ неод ед муж род 217778
абазу   сущ неод ед муж дат 217779
абаз    сущ неод ед муж вин 217780
абазом  сущ неод ед муж тв  217781
абазе   сущ неод ед муж пр  217782
абазы   сущ неод мн им  1261355
абазов  сущ неод мн род 1261356
абазам  сущ неод мн дат 1261357
абазы   сущ неод мн вин 1261358
абазами сущ неод мн тв  1261359
абазах  сущ неод мн пр  1261360

абазин  сущ одуш ед муж им  4155485
абазина сущ одуш ед муж род 4155486
абазину сущ одуш ед муж дат 4155490
абазина сущ одуш ед муж вин 4155487
абазином    сущ одуш ед муж тв  4155489
абазине сущ одуш ед муж пр  4155488
абазины сущ одуш мн им  4155491
абазин  сущ одуш мн род 4155492
абазинам    сущ одуш мн дат 4155494
абазин  сущ одуш мн вин 4155493
абазинами   сущ одуш мн тв  4155495
абазинах    сущ одуш мн пр  4155496

Я задаю, например, для поиска "абазы". Как только слово найдено мне надо вернуть "абаз    сущ неод ед муж им", т.е. самое первое слово в списке словоформ. Я делаю:
<!-- language: java -->
public class KazemirdoMatcher
{
    KazemirdoConverter kC = new KazemirdoConverter();

    private String[] requestWords;
    private Pattern p;
    private Matcher m;

    public void KazemirdoMatcherFirst() {
     try {
      File morph = new File("/home/virus/Documents/Workplace/Eclipse/Kazemirdo/Morph.txt");
      BufferedReader br = new BufferedReader
                (new InputStreamReader(new FileInputStream(morph), "Windows-1251"));
      // TODO: when matchs return infinitive
      String line = null;
      String match;
      requestWords = kC.getRequestBuffer();
      //
      for (int i = 0; i < requestWords.length; i++) {
        match = requestWords[i];
        while ((line = br.readLine()) != null) {
            p = Pattern.compile(match);
            m = p.matcher(line);
            if(m.find())
       // ????????????????????????????????????????????????
        }
       br.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "File not found:" + e);
            return;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Exception:" + ex);
            return;
        }
    }
}

Как мне вернуть именно первое слово из списка?
A: Никак. Вы уже проехали строку, которая содержит первую словоформу. Т.к. словоформы у вас сгруппированы и разделены пустыми строками, то запоминайте первую строку из группы и возвращайте ее при совпадении.
Если файл сам по себе небольшой, то загружайте его в память полностью, а словоформы сгруппируйте вместе. Так выборка будет работать быстрее.
А вообще здесь напрашивается дерево поиска, возможно суффиксное.
PS: Не надо компилировать Pattern каждый раз. Это достаточно сделать один раз перед циклом. В вашем случае паттерн вообще не нужен, т.к. можно использовать метод String.startWith. Работа вашего алгоритма зависит от порядка запрашиваемых слов. Т.о. возможнор ситуация, при которой алгоритм не вернет ничего для существующего слова. Например если масси запрашиваемых слов будет таким: "абазы", "абажурчики"
A: А что за класс тако Matcher? Можно код увидеть?
Так или иначе, на сколько я понял, результат нахождения нужной подстроки можно получить, проанализировав переменную m. m - экземпляр Matcher, в котором есть некий магический метод find(). Это метод наверняка ищет нужную подстроку в очередной считанной строке. Осталось только понять как оно там все хранится и вывести.
Если очередная считанная строка хранится просто как String, то предлагаю распарсить ее и вытащить нужное первое слово
A: Думается, что можно узнать строку, в которой ты сейчас(X), прочитать файл снова, запоминая последний номер строки с переносом(пустой строки)(Y), остановить цикл, когда дойдешь до строки (X),тогда (Y+1) будет твоя искомая строка.


text:
Q: Opening SQL dataset (PostgreSQL dump) I have a dataset downloaded from, point Database Dump:
http://aligulac.com/about/db/
Its a dataset with the ending .sql
I had a watch on similar stackoverflow questions asking this, but nothing worked. Like this:

*

*Tried the first own made function, but I get an error message.
How to read the contents of an .sql file into an R script to run a query?

*And I tried the function
read_file()
from the readr package.
Thanks


text:
Q: Speech Recognition/Dictation Crashing Process:               com.apple.SpeechRecognitionCore.speechrecognitiond [8448]
Path:                  /System/Library/PrivateFrameworks/SpeechRecognitionCore.framework/Versions/A/XPCServices/com.apple.SpeechRecognitionCore.brokerd.xpc/Contents/XPCServices/com.apple.SpeechRecognitionCore.speechrecognitiond.xpc/Contents/MacOS/com.apple.SpeechRecognitionCore.speechrecognitiond
Identifier:            com.apple.SpeechRecognitionCore.speechrecognitiond
Version:               2.2.7 (2.2.7)
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           com.apple.SpeechRecognitionCore.brokerd [738]

OS Version:            Mac OS X 10.11.4 (15E65)

Crashed Thread:        2  Dispatch queue: com.apple.root.default-qos

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x00000000000cf0ac
Exception Note:        EXC_CORPSE_NOTIFY

Dictation fails without notification, system log reveals above crash.

A: Steps to resolve the crash:

*

*Turn off enhanced dictation under the dictation system preference pane

*Turn off dictation

*Delete en_US.SpeechRecognition/ in /System/Library/Speech/Recognizers/SpeechRecognitionCoreLanguages/

*Turn on dictation and enhanced dictation, the recognizer is downloaded again

*Kill the speechsynthesisd and speechrecognitiond processes if dictation popup shows loading indefinitely


text:
Q: issue with react native local notification and play sound I'm creating react native app on googleplay im using react native pushNotification and react-native-sound
everything is work proper till the last update when I upload bundle on googleplay notification sound play with the sound that I use in one of react navigation page old AAB work fine but after updating this issue appears
when I clear data in android , notification sound works fine without any conflict
notification config is in App.js every thing is code proper and responsive
notification
 PushNotification.localNotificationSchedule({
      id: notificationId,
      title: lang.notificationRemaind,
      message: reminder.name, // (required)
      date: new Date(Date.now() + diffSeconds),
      allowWhileIdle: true,
      repeatType: 'week',
      channelId: 'Reminder',
      priority: 'max',
      soundName: 'remind',
    });

sound
            try {
                // play the file tone.mp3
                SoundPlayer.playSoundFile('firework', 'mp3')
            } catch (e) {
                console.log(`cannot play the sound file`, e)
            }

A: In my case, I did not use the library for notification sound.
Android:
step1: Add my_sound.mp3 file android/app/src/main/res/raw/my_sound.mp3
step2:

    PushNotification.localNotificationSchedule({

      title: lang.notificationRemaind,
      message: reminder.name,
      playSound: 'true'
      soundName: 'my_sound.mp3',
    });}

step3: for local notification add playSound  and SoundName in channel.

PushNotification.createChannel(
        {
            channelId: 'Test',
            channelName: 'test-channel',
            soundName: 'my_sound.mp3'
        }
    )

IOS:Add my_sound.mp3 file in xcode as pod level.


text: Q: How to compare granger causality with 2 stationary time series of different sizes? I want to compare 2 time series using granger causality. I found that one time series is stationary by itself without any transformations. But another time series requires differencing to make it stationary. How can I compare both time series then?


text:
Q: Are there any time-based events? In Fallout New Vegas, do I have to keep an eye on the time/date? Are there any events that happen after a certain amount of ingame time?
Can you for example miss something if you arrive to late in a certain place or don't finish a quest until a specific day?
I remember that in Fallout 1 or 2 (or both?) you were on a deadline and things could happen in the world without your interaction.

A: For the most part no. Some events will only resolve after a certain amount of time has been passed from a trigger, and you may occasionally need to let 3 days pass (or just wait in place 3 days) for a script reset or merchant restock, but there are no 'scheduled events' which require actual attention to the calendar.
A few quests can only be completed at night, or during the day, or at a certain time of day, but you can't 'miss' them, you'll merely need to wait for the time to roll around again.

A: Yes, there is one quest at Camp McCarran.

 You need to find and disable an explosive before time runs out.


text:
Q: MongoDB Search nested Objects without knowing Key I have a list of objects that are given somewhat arbitrary Object keys as a result of using the async Java driver + BSON.

My issue is given the fact that jobStatuses are an arbitrary list of Dictionary items where I don't know the key, I have no idea how to access its sub-values. In the end, I'm trying to build a query that returns if ANY of jobStatus.*._id are true given a list of potential Object ID's.
So I'd be giving a list of ID's and want to return true if ANY of the items in jobStatuses have any of the given ID's. Any ideas?

A: Let's try this :
db.yourCollectionName.aggregate([
    {
        $project: {
            _id: 0,
            jobStatutses: { $arrayElemAt: [{ $objectToArray: "$jobStatutses" }, 0] }
        }
    }, {
        $match: { 'jobStatutses.v._id': { $in: [ObjectId("5d6d8c3a5a0d22d3c84dd6dc"), ObjectId("5d6d8c3a5a0d22d3c84dd6ed")] } }
    }
])

Collection Data :
/* 1 */
{
    "_id" : ObjectId("5e06319c400289966eea6a07"),
    "jobStatutses" : {
        "5d6d8c3a5a0d22d3c84dd6dc" : {
            "_id" : ObjectId("5d6d8c3a5a0d22d3c84dd6dc"),
            "accepted" : "123",
            "completed" : 0
        }
    },
    "something" : 1
}

/* 2 */
{
    "_id" : ObjectId("5e0631ad400289966eea6dd1"),
    "jobStatutses" : {
        "5d6d8c3a5a0d22d3c84dd6ed" : {
            "_id" : ObjectId("5d6d8c3a5a0d22d3c84dd6ed"),
            "accepted" : "456",
            "completed" : 0
        }
    },
    "something" : 2
}

/* 3 */
{
    "_id" : ObjectId("5e0631cd400289966eea7542"),
    "jobStatutses" : {
        "5e06319c400289966eea6a07" : {
            "_id" : ObjectId("5e06319c400289966eea6a07"),
            "accepted" : "789",
            "completed" : 0
        }
    },
    "something" : 3
}

Output :
/* 1 */
{
    "jobStatutses" : {
        "k" : "5d6d8c3a5a0d22d3c84dd6dc",
        "v" : {
            "_id" : ObjectId("5d6d8c3a5a0d22d3c84dd6dc"),
            "accepted" : "123",
            "completed" : 0
        }
    }
}

/* 2 */
{
    "jobStatutses" : {
        "k" : "5d6d8c3a5a0d22d3c84dd6ed",
        "v" : {
            "_id" : ObjectId("5d6d8c3a5a0d22d3c84dd6ed"),
            "accepted" : "456",
            "completed" : 0
        }
    }
}

All you need is to check if at least one doc gets returned from DB for a given list or not, So we don't need to worry about document structure then just do result.length in your code to say at least one doc got matched for the input list.


text:
Q: Flutter The method 'map' was called on null. Receiver: null error I'm having this super annoying issue of being unable to grab and display a table from my server hosted on PhpmyAdmin. (I've managed to grab the data and have it printed in the console, but now that I'm trying to display it in a table I can't seem to get it working)
I've tried nulling my variables but I'm not really sure what the main culprit for this error is. Any help would be greatly appreciated.
Image of Error
data.dart File

class dataListing extends StatefulWidget {
  const dataListing({Key? key}) : super(key: key);

  @override
  State<dataListing> createState() => _dataListingState();
}

class _dataListingState extends State<dataListing> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class listingData{
  String? ListingID, listingName, listingDescription, address, suburbName, phoneNumber, openingHours, Email, Website;

  listingData({
    this.ListingID,
    this.listingName,
    this.listingDescription,
    this.address,
    this.suburbName,
    this.phoneNumber,
    this.openingHours,
    this.Email,
    this.Website,
  });
  //constructor
  List<listingData> datalist = [];
  factory listingData.fromJSON(Map<String, dynamic> json){
    return listingData(
      ListingID: json["ListingID"],
      listingName: json["listingName"],
      listingDescription: json["listingDescription"],
      address: json["address"],
      suburbName: json["suburbName"],
      phoneNumber: json["phoneNumber"],
      openingHours: json["openingHours"],
      Email: json["Email"],
      Website: json["Website"],
    );
  }
}

Directory.dart file
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:app/pages/data.dart';

class directoryPage extends StatefulWidget {
  @override
  State<directoryPage> createState() => _directoryPageState();
}

class _directoryPageState extends State<directoryPage> {

  // List serviceListing = [];
  //
  // getAllListing()async{
  //   String url = "URL HERE";
  //   var response = await http.get(Uri.parse(url));
  //   if (response.statusCode == 200){
  //     setState (() {
  //       serviceListing = json.decode(response.body);
  //     });
  //     print (serviceListing);
  //     return serviceListing;
  //   }
  // }
  bool error = false, dataloaded = false;
  var data;
  String dataurl = "URL HERE";

  @override
  void initState (){
    loaddata();
    super.initState();
    // getAllListing();
  }

  void loaddata() {
    Future.delayed(Duration.zero,() async {
      var res = await http.post(Uri.parse(dataurl));
      if (res.statusCode == 200) {
        setState(() {
          data = json.decode(res.body);
          dataloaded = true;

        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Directory'),
          centerTitle: true,
          elevation: 0,
          backgroundColor: Color(0xFFA30B32),
          //WSU Appbar Icon
          leading: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Image.asset("assets/wsulogo.png", scale: 8.0),
          ),
        ),
        body: Container(
          padding: EdgeInsets.all(15),
          child:dataloaded?datalist():
          Center(
            child:CircularProgressIndicator()
          ),
        )
    );
  }

  Widget datalist(){
    if(data["error"]) {
      return Text(data["errmsg"]);
    }else{
      List<listingData> datalist = List<listingData>.from(data["data"].map((i){
        return listingData.fromJSON(i);
      })
      );

      return Table( //if data is loaded then show table
        border: TableBorder.all(width:1, color:Colors.black45),
        children: datalist.map((listingdata){
          return TableRow( //return table row in every loop
              children: [
                //table cells inside table row
                TableCell(child: Padding(
                    padding: EdgeInsets.all(5),
                    child:Text(listingdata.ListingID!)
                )
                ),
                TableCell(child: Padding(
                    padding: EdgeInsets.all(5),
                    child:Text(listingdata.listingName!)
                )
                ),
                TableCell(child: Padding(
                    padding: EdgeInsets.all(5),
                    child:Text(listingdata.listingDescription!)
                )
                ),
                TableCell(child: Padding(
                    padding: EdgeInsets.all(5),
                    child:Text(listingdata.address!)
                )
                ),
              ]
          );
        }).toList(),
      );
    }
  }
}

A: Looks like the issue was actually unrelated to the dart side of things, the php code wasn't properly structuring the data. Cannot have underscores or spaces.
Correct-> $json["dballlisting"] = array (); (I renamed it to just "data" later)
Incorrect->$json["db_all_listing"] = array ();

A: The error seems to be originating from this line, the data['data'] is null which is expected to be an Array.
 List<listingData> datalist = List<listingData>.from(data["data"].map((i){
    return listingData.fromJSON(i);
  })

You need to investigate your API call to make sure why it is happening. If the null value is expected then you need to add safeguards in your code to make sure it won't break when it encounter such scenarios. You can add null safety checks for that one way to do it would be to
 List<listingData> datalist = List<listingData>.from((data["data"] ?? []).map((i){
    return listingData.fromJSON(i);
  })


text:
Q: ExtJS - Store Ajax response variable as a global I am trying to store the settings into the global variable.
var settings= {};

function on_ready() {
    Ext.Ajax.request({
         url: baseURL,

         success: function(response) {
             settings = Ext.decode(response.responseText);
         },

         failure: function(response) {
             console.log('server-side failure with status code ' + response.status);
         }
    });
}

console.log(settings);

The last line of code shows empty. I know that this is asynchronous call and thus it does not work. But don't know the solution. Is there a way how can I do this? I need to use this ˙settings˙ variable throughout my application. That's why it has to be global.

A: One approach we have used in the past for initializing settings before app start was using server-side templating for the html file. It did nothing more, but simply add a <script> block, and populated it with lines like window['prefix_propname'] = 'propvalue';. Not the most elegant way, but it worked fine.
But first, I'd rethink if you truly need it to be global. It's likely that you could simply have a data field in main's viewmodel with the settings (which are loaded on init of the main's controller), and then bind setting's parts as needed to the children via their config. Logic depending on the settings value then would be either in child's config update / apply methods, expressed via formulas with the settings as one of the parameters, or via a bind (inside view or controller). The bindings inside controller is a very handy feature, which comes up fairly often in my use, and it abstracts away the annoyance of having to deal with async loading; e.g.:
// view controller
init: function() {
  var vm = this.getViewModel();
  vm.bind('{settings}', function(settings) {
    //do your thing here
  });
}

A: All you need is a extjs singleton. Get the instance of singleton inside the success function and assign your settings to that singleton. Also there is an easier way to add singleton, i.e by adding settings in your window object.
success: function(response) {
             window["settings"] = Ext.decode(response.responseText);
}

Now you should be able to access the settings globally across the application.Still console.log will not have actual value because the will be other thread created for ajax call the present exection will continue without waiting for success function. You type "settings" after execution of "success" you'll see the contents.


text:
Q: $2$-Morphisms in the Fundamental $2$-Groupoid I'm trying to write down a clean definition of the fundamental $2$-groupoid $\pi_{\leq 2}(X)$ of a topological space $X$. Specifically, I'm concerned with how to properly define $2$-morphisms. Here is what I have:
The fundamental $2$-groupoid $\pi_{\leq 2}(X)$ is the strict $2$-category where

*

*The objects of $\pi_{\leq 2}(X)$ are the points of $X$.

*The $1$-morphisms $x\rightarrow y$ of $\pi_{\leq 2}(X)$ are the
continuous maps $f:[0,|f|]\rightarrow X$ with $f(0)=x$
and $f(|f|)=y$. Here $|f|\geq 0$.

*For $x\xrightarrow{f}y\xrightarrow{g}z$ define $g\circ f$ as the continuous
map $[0,|f|+|g|]\rightarrow X$ given by
$$
(g\circ f)(t)
=
\begin{cases}
f(t)         & 0\leq t\leq|f| \\
g(t-|f|) & |f|\leq t\leq|f|+|g|
\end{cases}
$$

Of course, we are deviating from the usual definition of a path as a map $[0,1]\rightarrow X$ to make the composition of $1$-morphisms associative on the nose. However, this seems to create a new problem. The $2$-morphisms should be homotopies of paths, but a homotopy between two maps is only defined if the maps have common domain and codomain. To remedy the situation, I've tried the following:

*

*For $x\xrightarrow{f}y$, let $\overline{f}:x\rightarrow y$ be the continuous map $[0,1]\rightarrow X$ given by $\overline{f}(t)=f(|f|\cdot t)$. Then the $2$-morphisms $\alpha:f\Rightarrow g$ in $\pi_{\leq 2}(X)$ are the continuous maps $\alpha:[0,1]\times[0,1]\rightarrow X$ with $\alpha(t,0)=\overline{f}(t)$, $\alpha(t,1)=\overline{g}(t)$, $\alpha(0,t)=x$, and $\alpha(1,t)=y$.

Is this the standard construction? I'm having trouble finding literature on this.

A: This is a question which raises all sorts of interesting issues!
I think it is easier to look for double groupoids rather than $2$-groupoids, because it is more symmetric with regard to directions and before taking homotopy classes of some kind, the notion of partial composition in a given direction is very clear, and extends to all dimensions.  See also this question on mathoverflow.
I though about this for 9 years starting in 1965 with the aim, as it seemed likely that the  proof I had written out many times for my topology book extended to get a $2$-dimensional van Kampen type theorem, and got myself quite confused. So it was "an idea for a proof in search of a theorem".
The breakthrough came with Philip Higgins in 1974 when,  as suggested by work of J H C Whitehead on second relative homotopy groups,  we started looking not at spaces but at pairs of spaces, $(X,A)$. So the natural idea was to look at maps of square $I^2$ into $X$ which took the vertices to the base point and edges into $A$.  Then all became easy,  not trivial, but easy. The details are in this book, which has a free pdf. A key picture for the definition of compositions being well defined is

The point is that that if $\alpha, \beta$ are two squares as above then their classes $[\alpha], [\beta]$ are homotopy classes rel vertices of maps $I^2 \to X$ where during the homotopies the boundary of $I^2$ stays in $A$. So $ \partial^+_2[\alpha] =\partial^2_-[\beta] $ means there is a homotopy $h$ of two loops in $A$, and such a homotopy is arbitrary. So when you try to prove independence of choices, you get the above figure, which has a big hole in the middle! But the bottom edges of the hole are all constant, so you can fill in the bottom square. Now fill in the hole by a retraction. All the faces of the "hole" are in $A$ so in the retraction the top face is also in $A$. So the whole block gives a homotopy $$\alpha +_2 h +_2 \beta \simeq \alpha' +_2 h'+_2 \beta'$$ of the type required.
This construction we called $\rho_2(X,A,a)$. It contains $\pi_2(X,A,a)$ . From this you can get as a substructure a $2$-groupoid, if you really want it.
There are papers dealing with the absolute case for Hausdorff spaces, see  K.A. Hardie, K.H. Kamps and R.W. Kieboom, 'A homotopy 2–groupoid of a Hausdorff space', Applied Cat. Structures 8 (2000), 209–234, and subsequent papers dealing with double groupoids in a related fashion.  But these papers have not it seems led to new calculations of homotopical invariants, as has the above relative construction.
Edit Feb 9, 2014: The above construction of a homotopy double groupoid of a pair is used to prove a $2$-dimensional van Kampen type theorem, one of whose consequences, an excision type theorem for second relative homotopy groups, is explained in my answer to  this stackexchange  question.


text:
Q: Show that energy is decreasing - PDE - Energy $ u_{tt}-u_{t}-u_{xx} =0\;,\;t>0\;,\;x\in(0,\pi)
\\
u(0,t)=u(\pi,t)=0,\; t>0
\\
E(t):= \frac{1}{2}\int_0^\pi(u_t^2(x,t)+u_x^2(x,t))dx.
\\
$
I solved this equation and I end up with something like that
$
E'(t)=\int_0^\pi (u_tu_{tt}+u_xu_{xt})\mathrm dx=\int_0^\pi (u_tu_{xx}+u_xu_{xt})\mathrm dx+\int_0^\pi (u_t)^2\mathrm dx$.
Since $\int_0^\pi (u_tu_{xx}+u_xu_{xt})\mathrm dx = \int_0^\pi(u_tu_x)_xdx=0$
we ended with $E'(t)=\int_0^\pi (u_t)^2\mathrm dx$. How can I show that   it is decreasing? thanks in advance


text:
Q: In Android Market , how frequently developers can/should update their apk files? What are the best practices on updating the apk files in the Android Market ? Is it ok to publish a new version as soon as i fix a minor glitch or should i consolidate a few bugs (if those or minor) and post it in a regular interval. Just released a game and got a extremely corner case crash issue and another minor glitch so i'm not sure if i release the fix right away.
Also are there any restrictions on the number of updates per time period ?
Even if there is no best practices as such could you (android developers) share how frequently you update your APK files for minor and major issues and what's your positive and negative experiences ?
Thanks!

A: Once a week is pretty optimal for generating new downloads and visibility. Based on my experiences and what I have read. Also weekends and holidays seem to generate more traffic.
I usually pack more changes into one update and release once in 1-2 weeks. Don't make updates if you have no real content. That may annoy users.
Read story #1: http://blog.edward-kim.com/an-android-success-story-13000month-sales-0
Read story #2: http://makingmoneywithandroid.com/2011/05/first-month-on-the-android-market/
People's experiences: Android Market - Time to wait between two updates
Market's "just in": http://www.google.bg/support/forum/p/Android+Market/thread?tid=5b8adbb9052fc55c&hl=en
Analysis when during day is most downloads: http://nhenze.net/?p=735
Discussion about time of day: Best time/day to publish to Android Market?

A: Personally, I think it depends on the type of application.  If you are coding a type of tool that obtains more and more functionality with each update, users probably won't mind the frequent updating.  Same goes for an application that has too many major bugs.
If you're coding a game though, I think updates relating to style of gameplay should be few and far-between.  Users get used to playing a certain way and could get annoyed if they have to keep adapting to what essentially is a different game every time they update.  Level pack updates are of course a different story though (I think those don't come fast enough sometimes).
Remember though, even if an update goes out for an app, it doesn't mean the user will download it.  I've seen too many friends with 22 updates available...  < drop down clear >

A: As far as I know you can update as often as you like. You pretty much have to decide what the balance is between annoying your users with frequent updates vs. making them happy by getting frequent bug fixes. For a while I was updating my own apps pretty much weekly and I never had any negative responses to that.


text:
Q: Adding MAKEFLAGS from MPC(The Makefile, Project, and Workspace Creator) I am using MPC to generate my makefiles. I generate successfully the Makefile but when I run make I get the following error:

error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.

My question is, how to add build flags (eg:-std=c++11) to my MPC?
For completion here is my MPC file:
project(Makefile) : dcpsexe, dcps_tcp {
   requires += no_opendds_safety_profile
   exename   = start
   after    += *idl

   TypeSupport_Files {
     Communication.idl
   }

   Source_Files {
     ListenerReader.cpp
     Publisher.cpp
     Subscriber.cpp
     main.cpp
   }
}

A: This can be done through the $ACE_ROOT/include/makeinclude/platform_macros.GNU file. Add a line with c++11=1 to the top of this file, that will enable C++11 support for the compiler.

A: Alternatively to enabling C++11 (or later) specifically for the platform this can be achieved on project basis, too, e.g.
specific(make) {
    compile_flags += -std=c++20
}

make has been selected according to MPC documentation, I haven't tested myself (but did for a MSVC project where it worked seamlessly) – possibly the undocumented gcc (or clang) compiler options might be supported as well (the equally undocumented vs2019 and vs2022 ones definitely are so), you'll have to try yourself...


text:
Q: How could I create a custom tabbar similar to segment control? How could I create a custom tabbar control similar to segment control at a bottom?
On the bottom, there are three tabs (tab1,tab2 and tab3). Tab show like segment control. Every segment index is selected, the navigation bar show will have different views.
Any help or insight into how to achieve this would be great.

A: you can use Images like you want to set as a background of your UITabBar...
otherwise use custom UITabBarController , see bellow some links..

*

*custom-uitabbarcontroller-for-the-iphone

*iphone-app-implement-a-custom-tab-bar

*how-to-make-tabbar-in-iphone-sdk code

*RXCustomTabBar

*Custom TabBar /// see this links with many types of UITabBar..
i hope this help you..


text:
Q: Android: данные из AsyncTask 2 Опять обращаюсь с проблемой, когда из образа класса беру значение переменной, в этом классе нужное мне значение,а в активити куда я его передаю - null (или стандартное значение). Пробовал юзать интерфейс - не помогло. Класс:
   public class ShowBar extends AsyncTask<URL, Integer, Long>
{
   ProgressDialog mProgressDialog;
   public String info = "que-";
   private  boolean today = true;
   private Context  context_dialog;

   public ShowBar(Context context, boolean day)
   {
      context_dialog = context;

      today = day;
   }

   @Override
   protected void onProgressUpdate(Integer... values) {
       super.onProgressUpdate(values);    //To change body of overridden methods use File | Settings | File Templates.
   }

   @Override
   protected void onPostExecute(Long aLong) {
       super.onPostExecute(aLong);
       mProgressDialog.dismiss();
       FootballView foot = new FootballView();
       foot.OnComplete(this.info);
       //foot.info = this.info; // тоже null

   }

   @Override
   protected void onPreExecute() {
       mProgressDialog =
               ProgressDialog.show
                       (context_dialog
                               , "Загрузка"
                               , "Подождите, идёт загрузка", true);

       mProgressDialog.setCancelable(false);
       mProgressDialog.show();
   }

   @Override
   protected Long doInBackground(URL... urls) {
       long result = 0;
       Elements links;

       final String URL = "http://ya.ru";

       if (today)
           {

               Document doc = null;
               try {
                   doc = Jsoup.connect(URL).get();
                   links = doc.select("table[class=translation]");
                   info =  links.outerHtml();

               }catch (Exception e){

               }
           }

       return result;

   }

}

Активити:
    public class FootballView extends ListActivity implements View.OnClickListener, OnCompleteListener {
    ...
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
           button1 = (Button) findViewById(R.id.TodayYesterday);
           button1.setOnClickListener(this);
           textView1 = (TextView) findViewById(R.id.mainView1);

              bar = new ShowBar(this,true);

              bar.execute();

    }

@Override
    public void OnComplete(String infos) {

        info = infos;

    }

Интерфейс:
public interface OnCompleteListener {
    void OnComplete(String infos);
}

Думаю с интерфейсом творю что-то не то =(
A: Думаю так будет лучше.
@Override
       protected Long doInBackground(URL... urls) {
           //...
           return nill;
       }

//
 final String URL = "http://ya.ru";
    bar.execute(URL);


text: Q: importlib.find_loader() module in python What is importlib.find_loader() module in python what can be an appropriate example for beginners? while using the importlib package in python I am not able to understand the use of find_loader() module of python . What can be a simple example to clear the doubts and get complete knowledge of importlib.find_loader()?


text:
Q: How to avoid page break inside tr? How to avoid page break inside <tr>?
(ANGULAR PROJECT) I have table (PrimeNG table) and I want to avoid break after print page.
I use Chromium/Chrome browse.
After print I have this result:

So, how to avoid this, or how to disable repeat thead?
I tried this links, but dosen't work:
How to avoid page break inside table row for wkhtmltopdf
"page-break-inside: avoid "- does not work
avoid page break inside row of table

A: I have same problem.
This combination helped me
@media print {
    html, body {
        width: 210mm;
        height: auto;
    }

    body {
        margin: 10mm 15mm 10mm 15mm; /* margin you want for the content */
    }

    p, img, a, div.image, div{
        page-break-inside: avoid;
    }

    table, thead, tbody, tr, td, th, label, strong{
        page-break-inside: auto;
    }
}

A: The following is what worked in Chrome to:

*

*Prevent table cell contents from being split across a page break.

*Prevent table rows from having arbitrary vertical gaps between them a few rows after each page break.

@media print {
  tr, td {
    break-after: auto;
    break-inside: auto;
    line-height: 1;
  }
}


text:
Q: Update query in Cassandra 2.3 This is My Table structure as follows
CREATE TABLE manage_files_log (
    account_sid uuid,
    file_type text,
    file_sid timeuuid,
    date_created timestamp,
    file_description text,
    file_name text,
    status int,
    url text,
    PRIMARY KEY ((account_sid, file_type), file_sid)
) WITH CLUSTERING ORDER BY (file_sid DESC)

in this table I want to update my records with query
UPDATE manage_files_log SET url='$url' WHERE account_sid =e40daea7-b1ec-088a-fc23-26f67f2052b9 AND file_type ='json' AND file_sid=961883e0-208f-11e6-9c41-474a6606bc87;

but it is inserting new record instead of updating existing record.
please help Me
below is the example of data in table where I want to update the url column value
account_sid                          | file_type | file_sid                             | date_created             | file_description | file_name | status | url
--------------------------------------+-----------+-------------------    -------------------+--------------------------+------------------+--------    ---+--------+-----
 e40daea7-b1ec-088a-fc23-26f67f2052b9 |      json | e15e02f0-20ab-11e6-9c41-474a6606bc87 | 2016-05-22 00:00:00+0000 |      descripton  |  testUrl1 |      1 |

A: Okay, there's one thing you have to know about cassandra: Update or insert don't exist. I know, you write, in your query, update or insert, but it's the same. It's called Upsert. You might think: Whaaat? But there's a reason for this: Cassandra is a masterless distributed database system. You have, generally, no transactions. If you insert a value to node1 and want to update it after 10ms on node2, it could happen that your first value isn't on node2. With a hard UPDATE, your second operation will fail. But cassandra ignores this fact and writes the values to node2. After a time node2 and node1 will synchronizing their values. At this stage node1 gets the right values from node1. (Cassandra uses an internal column timestamp for synchronizing)
But you can also use update as update: Simply add IF EXISTS; to your query. But remember one thing: It's a big performance killer. Cassandra has to read all values from all nodes!


text:
Q: Effect of TextView display by setting Theme.NoTitleBar I am confused that why i set android:theme="@android:style/Theme.NoTitleBar" in AndroidManifest.xml for didn't want the titlebar shown in screen when the app works and why it will effect text in textview??
the titlebar is disappear in my app, BUT in my app, i can select one of object as focused, this object has a imageview and a textview.
problem is when a object is selected, the text in textview in this object also disappear too....didn't shown in monitor, but if i select another object the text appear again.
Thanks & Regards


text:
Q: Integral solution to an equation For what largest value of $X$ would $$(4X-1)/5 ,(4X-2)/6 ,(4X-3)/7 $$give integers such that $$4x+2$$ is a four digit number ?
My approach:
In somewhat convoluted way ,let a=4x-1 etc or a is a number which leaves remainder 1 when divided by 4, b leaves remainder 3 when divided by 5 , c leaves 5 when divided by 7.
Lcm of 4,5,7 should be multiplied by largest possible number till we get a four digit number, then subtract 2 from it and we are done.
But obviously, its more like hit and trail and not mathematics.
Any other better solution will be appreciated.

A: The problem is solved using the Chinese Remainder Theorem (CRT), but since that requires coprime moduli, we have to begin by replacing $4x$ with $y$ and later looking at which solutions for $y$ are multiples of $4$.
First, let's restate the divisibility properties in terms of modular arithmetic: $$5\mid (4x-1) \Rightarrow y\equiv 1 \bmod 5$$
$$6\mid (4x-2) \Rightarrow y\equiv 2 \bmod 6$$
$$7\mid (4x-3) \Rightarrow y\equiv 3 \bmod 7$$
By CRT, there is one number smaller than $5\cdot 6\cdot 7=210$ that satisfies those conditions, and that number is $206$. We can find that number by first considering numbers which are $\equiv 1 \bmod 5$. Those are $6,11,16,21,26,\dots$. Note that they occur every five apart. Next identify the members of that list that are $\equiv 2 \bmod 6$. Those are $26,56,86,116,\dots$. They occur every $5\cdot 6=30$ apart. Finally from that list identify the number that is $\equiv 3 \bmod 7$. It is $206$. Numbers that meet all three conditions will be spaced $5\cdot 6\cdot 7=210$ apart. They will have the form $y=206+210k$.
Neither $206$ nor $210$ is divisible by $4$. But the sum $y=206+210k$ will be divisible by $4$ when $k$ is odd. So we can say that $4x=416+420n$. You wish to identify the largest occurrence of this number less than $9999$.
$416+420n<9999 \Rightarrow n<\frac{9999-416}{420}=22.82$. So for integer value, $n=22$, $4x=9656$, $x=2414$, and $4x+2=9658$.


text:
Q: Как можно на svg нарисовать бесконечную линию зная две её точки? Как можно на svg нарисовать бесконечную линию зная две её точки?
Мне нужно чисто визуальное отображение, но со всеми стилями для линии.
<svg width="500px" height="500px">
   <line x1="100" y1="80" x2="100" y2="20" stroke="black" />
</svg>

Точки линии, ширина, высота svg, viewBox могут меняться javascript'ом, но надо чтобы она в любом случае отображалась бесконечной. Желательно обойтись только HTML и CSS.

A: Бесконечную линию нарисовать вряд ли получится :), однако можно нарисовать линию на всем видимом диапазоне холста.
Для этого понадобится уравнение прямой:

y = kx + b, где k = dY/dX

Подставим в это уравнение значения исходных точек, и выразим y от х и x от y
  k = (y2 - y1) / (x2 - x1)
  fX = x => y1 + (x - x1) * k
  fY = y => x1 + (y - y1) / k

Далее путем не хитрых подстановок находим точки пересечения прямой проходящей через исходные точки и границ холста.

let x, y, cur;

document.querySelectorAll('circle').forEach(c => c.onmousedown = e => {
  cur = c;
  x = +c.getAttribute('cx') - e.x;
  y = +c.getAttribute('cy') - e.y;
});

addEventListener('mouseup', e => cur = null);

addEventListener('mousemove', e => {
  if (!cur) return;
  cur.setAttribute('cx', x + e.x)
  cur.setAttribute('cy', y + e.y)
  move();
});

move();

function move() {
  let x1 = +p1.getAttribute('cx'),
      y1 = +p1.getAttribute('cy'),
      x2 = +p2.getAttribute('cx'),
      y2 = +p2.getAttribute('cy'),
      w = +svg.getAttribute('width'),
      h = +svg.getAttribute('height'),
      k = (y2 - y1) / (x2 - x1),
      fX = x => y1 + (x - x1) * k,
      fY = y => x1 + (y - y1) / k;
  let pt1 = check([0, fX(0)]);
  let pt2 = check([w, fX(w)]);
  l.setAttribute('points', `${pt1[0]} ${pt1[1]} ${pt2[0]} ${pt2[1]}`);
  pA.setAttribute('cx', pt1[0]);
  pA.setAttribute('cy', pt1[1]);
  pB.setAttribute('cx', pt2[0]);
  pB.setAttribute('cy', pt2[1]);

  function check(p) {
    if (p[1] < 0)
      return [fY(0), 0];
    if (p[1] > h)
      return [fY(h), h];
    return p;
  }
}
<svg id="svg" width="500" height="170" style="border:solid">
   <polyline id="l" stroke="red" stroke-width="2"></polyline>
   <circle id="p1" cx="100" cy="60" r="10"></circle>
   <circle id="p2" cx="200" cy="40" r="10"></circle>
   <circle id="pA" r="10" fill="red"></circle>
   <circle id="pB" r="10" fill="red"></circle>
</svg>

A: Так же возможно получить подобный эффект за счет фокуса в svg, суть которого в применении многократного масштабирования, единственное что нужно посчитать, это центр между двумя исходными точками, относительно которого и необходимо масштабировать.
При этом так же необходимо установить атрибут vector-effect="non-scaling-stroke", который будет препятствовать визуальному увеличению толщины линии при масштабировании.
Но этот способ конечно хуже, т.к. когда точки близко друг к дружке, можно получить некорректный результат

let x, y, cur;

document.querySelectorAll('circle').forEach(c => c.onmousedown = e => {
  cur = c;
  x = +c.getAttribute('cx') - e.x;
  y = +c.getAttribute('cy') - e.y;
});

addEventListener('mouseup', e => cur = null);

addEventListener('mousemove', e => {
  if (!cur) return;
  cur.setAttribute('cx', x + e.x)
  cur.setAttribute('cy', y + e.y)
  move();
});

function move(){
  let x1 = +p1.getAttribute('cx'),
      y1 = +p1.getAttribute('cy'),
      x2 = +p2.getAttribute('cx'),
      y2 = +p2.getAttribute('cy'),
      cx = (x1 + x2)/2,
      cy = (y1 + y2)/2;
  l.setAttribute('transform', `translate(${cx},${cy})scale(1000)translate(${-cx},${-cy})`);
  l.setAttribute('points', `${x1} ${y1} ${x2} ${y2}`)
}

move();
<svg id="svg" width="500" height="170" style="border:solid">
   <polyline id="l" stroke="red" stroke-width="2" vector-effect="non-scaling-stroke"></polyline>
   <circle id="p1" cx="100" cy="60" r="10"></circle>
   <circle id="p2" cx="200" cy="40" r="10"></circle>
</svg>


text:
Q: Consumir XML con web service usando Laravel Estoy comenzando mi proyecto de tesis y salió este tema nuevo para mi. Los web services.
Básicamente, necesito construir un web service en laravel, que me permita trabajar unos archivos xml que me enviará SAP y que contienen la info de vehículos que van entrando a taller.
El xml es el siguiente:
    <?xml version="1.0" encoding="UTF-8"?>
<OrdenIngreso xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<NumeroPedido>0201932214</NumeroPedido>
<Patente>JP-JP97</Patente>
<Chasis>WDDBF4DB5XX510012</Chasis>
<FechaEntrega>201XX426</FechaEntrega>
<RutAsesor>96682XX-1</RutAsesor>
<NombreAsesor>Chris Allikson Maturana Santander</NombreAsesor>
<CodigoCanal>34</CodigoCanal>
<CodigoMarca>01</CodigoMarca>
<DescripcionMarca>Mercedes-Benz</DescripcionMarca>
<CodigoModelo>176043A</CodigoModelo>
<DescripcionModelo>A 200</DescripcionModelo>
<CodigoCiaSeguro>0001017074</CodigoCiaSeguro>
<DescripcionCiaSeguro>CHILENA CONSOLIDADA SEGUROS GENERAL</DescripcionCiaSeguro>
<Cliente>KAUFMANN S.A. VEHICULOS MOTORIZADOS</Cliente>
<CodigoColor>191</CodigoColor>
<DescripcionColor>NEGRO COSMOS</DescripcionColor>
<TipoPedido>ZS12</TipoPedido>
<DescripcionTipoPedido>OT aseguradora</DescripcionTipoPedido>
<CodigoSucursal>1181</CodigoSucursal>
<DescripcionSucursal>Sucursal Santiago</DescripcionSucursal>
</OrdenIngreso>

Una vez recibido, ya tengo que ver como lo trabajo, para guardar esta info en base de datos en caso de que no exista.
Estoy trabajando con laravel 5.8 y mysql
Desde ya cualquier comentario, bienvenido y gracias.

A: Hola como estas Francisco te mostrare como leo yo los archivos XML con laravel, tomando en cuenta que esos xml serán standard:

*

*Primero debes guardar el archivo en el disco local storage/vehiculos (por ejemplo)

*Luego cargas DOMDocument como el ejemplo abajo
$dom = new DOMDocument;
  $dom->load("ruta donde esta el archivo". "nombre del archivo" . '.xml');

*una vez ya cargado el archivo lo tienes en $dom y puedes sacar elemento por elemento.
$NumeroPedido = $dom->getElementsByTagName("NumeroPedido")[0];
$Patente = $dom->getElementsByTagName("Patente")[0];

*Luego ya lo guardas en la base de datos que crees para almacenar la información
Vehicules::create(['numero_pedido'=>$numeroPedido->nodeValue,'patente'=>$Patente->nodeValue]);
Me parece que con eso puedes hacer lo que necesitas.


text:
Q: Add web part in Wiki page in Edit mode issue I am facing issue of web part(CEWP) provisioning in wiki page programmatically.
Web part added successfully in wiki page in display mode using below code:
 string markup = string.Format(CultureInfo.InvariantCulture, "

", new object[] { wpStorageKey.ToString("D") });

Web part property is generated perfect as we want.
but When I am going to opening in web part in edit mode to change the property . Web part is not added in edit mode.But using Contents=1 I can see web part exists in page.
I have tried below method also. Method is very helpful for me but it is generating odd even HTML which is damn complex.
WikiEditPage.InsertWebPartIntoWikiPage(existingFile, cewp, 10);

Anyone can help me out of this!! It's really a headache.

A: SharePoint Object Model suggests to use WikiEditPage.InsertWebPartIntoWikiPage method for this purpose.
But looks like it works incorrect: Position parameter is processed by the wrong way and you get non-working page after update.
Insert call corrupts original WikiField value because, for instance, if your position =2, you get failed HTML. Even your position=0 and Wiki page looks nice - you cannot edit it.
So I don't recommend to use InsertWebPartIntoWikiPage in your work
You can write own implementation which insert new webpart in the correct place: in div with ms-rte-layoutszone-inner class.
Please check below link
http://maxshulga.blogspot.in/2010/06/wikieditpageinsertwebpartintowikipage.html
Hope you get it to work.


text:
Q: Quando troco o valor de um ComboBox todos mudam Tenho um banco de dados com duas tabelas, Tab1 e Tab2.
Na Tab 1 eu tenho Cd_Tab1 e Nm_Objeto.
Na Tab2 eu tenho Cd_Tab2, Cd_Tab1.
As duas estão relacionadas.
No meu projeto tenho 4 ComboBox, todas devem representar o valor de Cd_Tab2, mas cada uma irá gravar um novo Cd_Tab2(Ex: Primeira Cmb = Cd_Tab2(1), Segunda Cmb = Cd_Tab2(2) etc...
O problema que estou tendo é que quando eu mudo o valor de uma cmb no projeto todas as outras mudam junto.
Codigo XAML:
<ComboBox x:Name="btCmbAtkBaAtr2" HorizontalAlignment="Left" Margin="0,79,0,0"
            VerticalAlignment="Top" Width="50" DisplayMemberPath="Nm_Objeto"
            ItemsSource="{Binding Source={StaticResource Tab1ViewSource}}"
            SelectedValuePath="Cd_Tab1"
            SelectedValue="{Binding Cd_Tab1, Source={StaticResource Tab2ViewSource}}"/>
<ComboBox x:Name="btCmbAtkBaAtr2" HorizontalAlignment="Left" Margin="0,79,0,0" VerticalAlignment="Top" Width="50" DisplayMemberPath="Nm_Atr" ItemsSource="{Binding Source={StaticResource atributosNormaisViewSource}}" SelectedValuePath="Cd_AtributosNormais" SelectedValue="{Binding Cd_AtributosNormais, Source={StaticResource ataquesBasicosViewSource}}"/>
<ComboBox x:Name="btCmbAtkBaAtr3" HorizontalAlignment="Left" Margin="0,121,0,0" VerticalAlignment="Top" Width="50" DisplayMemberPath="Nm_Atr" ItemsSource="{Binding Source={StaticResource atributosNormaisViewSource}}" SelectedValuePath="Cd_AtributosNormais" SelectedValue="{Binding Cd_AtributosNormais, Source={StaticResource ataquesBasicosViewSource}}"/>
<ComboBox x:Name="btCmbAtkBaAtr4" HorizontalAlignment="Left" Margin="0,163,0,0" VerticalAlignment="Top" Width="50" DisplayMemberPath="Nm_Atr" ItemsSource="{Binding Source={StaticResource atributosNormaisViewSource}}" SelectedValuePath="Cd_AtributosNormais" SelectedValue="{Binding Cd_AtributosNormais, Source={StaticResource ataquesBasicosViewSource}}"/>

Tab1:

Tab2:


text:
Q: C++ linked list based tree structure. Sanely copy nodes between lists edit
Clafification: The intention is not to remove the node from the original list. But to create an identical node (data and children wise) to the original and insert that into the new list. In other words, a "move" does not imply a "remove" from the original.
endedit
The requirements:

*

*Each Node in the list must contain a reference to its previous sibling

*Each Node in the list must contain a reference to its next sibling

*Each Node may have a list of child nodes

*Each child Node must have a reference to its parent node

Basically what we have is a tree structure of arbitrary depth and length. Something like:
-root(NULL)
--Node1
----ChildNode1
------ChildOfChild
--------AnotherChild
----ChildNode2
--Node2
----ChildNode1
------ChildOfChild
----ChildNode2
------ChildOfChild
--Node3
----ChildNode1
----ChildNode2

Given any individual node, you need to be able to either traverse its siblings. the children, or up the tree to the root node.
A Node ends up looking something like this:
class Node
{
  Node* previoius;
  Node* next;
  Node* child;
  Node* parent;
}

I have a container class that stores these and provides STL iterators. It performs your typical linked list accessors. So insertAfter looks like:
void insertAfter(Node* after, Node* newNode)
{
  Node* next = after->next;
  after->next = newNode;
  newNode->previous = after;
  next->previous = newNode;
  newNode->next = next;
  newNode->parent = after->parent;
}

That's the setup, now for the question. How would one move a node (and its children etc) to another list without leaving the previous list dangling?
For example, if Node* myNode exists in ListOne and I want to append it to listTwo.
Using pointers, listOne is left with a hole in its list since the next and previous pointers are changed. One solution is pass by value of the appended Node. So our insertAfter method would become:
void insertAfter(Node* after, Node newNode);
This seems like an awkward syntax. Another option is doing the copying internally, so you'd have:
void insertAfter(Node* after, const Node* newNode)
{
  Node *new_node = new Node(*newNode);
  Node* next = after->next;
  after->next = new_node;
  new_node->previous = after;
  next->previous = new_node;
  new_node->next = next;
  new_node->parent = after->parent;
}

Finally, you might create a moveNode method for moving and prevent raw insertion or appending of a node that already has been assigned siblings and parents.
// default pointer value is 0 in constructor and a operator bool(..)
// is defined for the Node

bool isInList(const Node* node) const
{
  return (node->previous || node->next || node->parent);
}
// then in insertAfter and friends
if(isInList(newNode)
  // throw some error and bail

I thought I'd toss this out there and see what folks came up with.

A: Let's call the node that we are going to remove current. Only the nodes pointed to by current, namely current->previous, current->next, current->child, and current->parent refer to the node current. For example, current->previous->next == current if the current node's previous node is non-null. So, we can easily excise the current node from the list like so:
Vertical Links
A node keeps its children, but it needs to be excised from its parent. This is done like so:
Let parent = current->parent
if parent is non-null:
    if parent->child == current:
         parent->child = current->next
current->parent = null

Horizontal Links
The following code unlinks the current node in the horizontal (next/previous) direction:
Let prev = current->previous
Let next = current->next
if prev is non-null:
    prev->next = next
if next is non-null:
    next->previous = prev
current->previous = null
current->next = null

Granted, this is still a bit messy, but if you break the linked list functionality into small functions (which it looks like you are already doing) and use good comments, then it's really not that bad, I don't think.

A: First, I agree that, if you're copying the node and not actually removing it from the original tree, the operation should be called a copy, not a move!
Second, I recommend you separate the operation that actually does the copying from the operation that does insertion. This will make it much more flexible, if say for example you need to insert nodes from other sources into your destination, or you want to copy the node for other purposes.
Third, you didn't specify whether Node is polymorphic. If it is, I would implement a method like the following to do the copy:
virtual Node* clone();

You have a couple of design decisions to make here:

*

*Do you want to preserve next, prev, and parent when you do a clone? I think it makes sense to zero them out.

*Do you want to do a deep copy of the children as well when you do a clone? Depending on the use case, you may want to do one or the other, or allow for both.

Fourth, you assume that insertion should fail if the parent/prev/next pointers are already set. You can do this, but you may benefit down the road from a more powerful insertion operation that simply removes nodes from their existing tree in this case. Either will behave consistently.
Fifth, you can't be passing const Nodes around if you're going to be fixing up that node's pointers.
Let's assume for the moment that you decide to zero out the linked list pointers but decide to deep copy the children. Then your code might look like:
class Node {
public:
    Node() : prev(NULL), next(NULL), parent(NULL), child(NULL) { }
    virtual Node* clone() {
        Node* newN = new Node();
        newN->cloneChildren(*this);
        return newN;
    }
    Node* lastChild() const { /* left as exercise */ }
    void insert(Node* node_) { insertAfter(node_, lastChild()); }
    void insertAfter(Node* node_, Node* prevSibling_) {
        ASSERT(node_);
        if (! prevSibling_) { // assume we want to push to front of child list
           prevSibling_ = child; // will be NULL if we have no children
        }
        ASSERT(! prevSibling_ || prevSibling_->parent == this);
        if (node_->parent) {
            // assume you want to move the child in this case
            node_->parent->remove(node_);
        }
        node_->parent = this;
        node_->prev = prevSibling_;
        if (prevSibling_) {
            node_->next = prevSibling_->next;
            prevSibling_->next = node_;
        } else {
            /* the new child is the only child - left as exercise */
        }
    }
    void remove(Node* child_) { /* left as exercise */ }
protected:
    virtual void cloneChildren(const Node& rhs) { /* left as exercise */ }
};

And the code that does the copying from one tree to another simply looks something like:
Node* myNode = ...
Node* someChildInListTwo = findPlaceToInsert(listTwo);
listTwo->insertAfter(myNode->clone(), someChildInListTwo);

In this case we have turned your one somewhat tangled operation into a set of discrete operations that you can use in a wide variety of cases:

*

*a clone() operation that allows you to copy arbitrary nodes, whether or not they've been added to trees yet

*an insert() operation that will automatically do a move for you if you want, and correctly handles adding to the front of the child list

*a remove() operation that fell out naturally as a byproduct of how we wanted insertion to behave, but which can be used on its own

*a simple mechanism to copy+insert the node if you don't want to remove the node from the original tree


text:
Q: Bluemix: Node.js + Watson Concept Expansion API I am trying to use the Watson Concept Expansion example app that was listed with the CE Documentation page from IBM DevOps Services.
The app generates an error when it tries to retrieve the results and I think I see why but am unsure what to do about it:
Here is the applicable code for retrieving the results:

// Get the job result by calling PUT to '/result' with the jobid
var job_result_async = function(jobid, onSuccess, onError) {
  // create a new map with the defaault https params
  var params = extend({},default_params);
  params.path += '/result';
  params.method = 'PUT';

  var watson_req = https.request(params, function(result) {
    var response_string = '';

    result.on('data', function(chunk) {
      response_string += chunk;
    });

    result.on('end', function() {
      var result_json = JSON.parse(response_string);

      // format results if exists
      if (util.isArray(result_json.return_seeds)) {
        var result_clean = result_json.return_seeds.map(function(e) {
          return { 'result' : clean_string(e.result),
            'prevalence': e.prevalence }
        });
      result_json.return_seeds = result_clean;
              }

      onSuccess(result_json);
    })

  });

  watson_req.on('error', function(e) {
    onError(e)
  });

  // send the data
  watson_req.write(JSON.stringify({'jobid': jobid}));
  watson_req.end();
};

Here is the documentation page for the /result REST API endpoint:
Concept Expansion REST API for /result
In the function the jobid is never being passed as far as I can tell. I suspect this is the problem but if anyone can confirm this that would be great, and also I am unclear how I would pass the jobid to the /result API to be able to retrieve the results.
Thank you for any assistance!
-Andy

A: The service was having issues when you tried few days ago. Looking at your code it should work.
If you want to try the service you can use the watson-developer-cloud npm module as described below:
var watson = require('watson-developer-cloud');

var concept_expansion = watson.concept_expansion({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});

var params = {
  seeds: ['motrin','tylenol','aspirin'],
  dataset: 'mtsamples',
  label: 'medications'
};

concept_expansion.expand(params, function (err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

I run the code above and got:
{
  "return_seeds": [
    {
      "prevalence": "2.803636",
      "result": "penicillin"
    },
    {
      "prevalence": "2.748252",
      "result": "plan: 1"
    },
    {
      "prevalence": "2.685714",
      "result": "actos"
    },
    {
      "prevalence": "2.670330",
      "result": "lipitor"
    },
    {
      "prevalence": "2.649351",
      "result": "zocor"
    },
    {
      "prevalence": "1.400000",
      "result": "ibuprofen 200 mg three pills"
    },
    ...
  ]
}

Concept-Expansion demo: http://watson-ce-demo.mybluemix.net/


text: Q: how to prevent the visual studio from automatic publishing of my source code when choosing 'publishing on web deploy' option? I want to publish my web project to IIS server but my cs files form my controller folder and other places are copied too automatically. when publishing ,I ticked "only copy needed files " and "precompile before publish" check boxes. How to prevent it?


text:
Q: How can i install nextcord without uninstalling discord.py? I run a discord server where i have a win10 spare pc that runs my discord bots (not looking for advice, looking for an answer)
and i have a discord bot coded in nextcord but i can't run my other discord bots when i run the nextcord bot, because i'd have to uninstall discord.py to run nextcord. any fixes on how to run discord.py bots side by side with a nextcord bot?
DistributionWarning: discord.py is installed which is incompatible with nextcord. Please remove this library by using pip3 uninstall discord.py

  warn(message, DistributionWarning, stacklevel=0)


text:
Q: Optimizing this code to find & factorize triangle numbers So, I know if I
A) Let this run all night with an Upper Bound of 10,000,000
or
B) Change the range of n in increments of 500
I can get the answer to this Euler problem. But both of those feel like cheating / lazy. I've seen other solutions to this posted in C, but not in Python.
My main areas of optimization here would presumably be either/or/both some better manner of summing all integers up to a certain value, and not having Python constantly creating and dumping the list of factors for every single number it's checking. Having waited 20 minutes with an Upper Bound of one million and the program not completing, I'm not happy with the way I've implemented this.
    for x in range(1,SomeUpperBound):
        n = sum(range(1,x))
        factorize(n)

def factorize(n):
    for i in range(1,n+1):
        if n > 1 and n % i == 0 and i not in factors:
            factors.append(i)
            if len(factors) == 500:
                print(n)
                print(factors)
    else: factors.clear()


text:
Q: In a finite cyclic group, the generator has the order of the group Let $G$ be a finite cyclic group of order $n$ generated by an element $g$. I want to show that the order of $g$ is exactly the order of $G$.
My try:
We can write $G=\{g^i\;|\;i\in \mathbb Z\}$. Since $G$ is finite, we know that there will be identifications $g^i=g^j$ that will make $G$ finite. By the multiplication law on $G$ we must have $g^0=1$. Also if $i<j$ and if $g^i=g^j$ then $g^{j-i}=1$. I can see all these but not see why $g^n=1$ and not $g^k=1$ for all $0<k<n$? Thank your for your help!!

A: If $g\in G$ has order $k$ then set $\left\{ e,g,\ldots,g^{k-1}\right\} $ has distinct elements and $\left\{ g^{i}\mid i\in\mathbb{Z}\right\} =\left\{ e,g,\ldots,g^{k-1}\right\} $.
Here $e$ stands for the identity of $G$.
If secondly $G$ is generated by $g$ then $G=\left\{ g^{i}\mid i\in\mathbb{Z}\right\} =\left\{ e,g,\ldots,g^{k-1}\right\} $
and consequently $\left|G\right|=k$, i.e., the order of $G$ is exactly
the order of $g$.


text:
Q: How to sort a SET of strings and store the result How do I sort a SET in redis and store the result as a SET and not as a list?
sadd myset "a" "b" "g" "w"
sort myset ALPHA STORE myset_tmp
type myset_tmp
> list

A: You CANNOT do that. The destination of sort must be a list.
Also, it doesn't make any sense to store the result into another set. The set you want, is just a copy of the original set. So the sort is redundant.


text:
Q: Jupyter notebook exclamation mark arguments In jupyter notebook, we can execute a shell command using the exclamation mark, such as:
!ls *.png

I am looking for a way to pass arguments to this command, something like:
extention='*.png'
!ls %extention

I know this is possible using os.system or subprocess.check_output, but I want to use the exclamation mark as this will give me live output.

A: This is possible using {}, such as:
extention='*.png'
!ls {extention}


text:
Q: Issue with Global.asax.cs file and StyleCop rule SA1649 Currently I'm working on a project at work and we're looking at upgrading our StyleCop from version 4.3.3 to 4.5
During the fun of all that, we've come across rule SA1649 - "FileHeaderFileNameDocumentationMustMatchTypeName" which is all nice and that, but causes issues with Global.asax.cs files, in that the file
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="COMPANY">
//   Copyright (c) COMPANY. All rights are reserved.....
// </copyright>
// <summary>
//   Starting point for back office website.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Foo.Web
{
    /// <summary>
    /// Starting point for back office website.
    /// </summary>
    public class MvcApplication : HttpApplication
    {
        ....
    }
}

Is being complained about because the file name 'Global.asax.cs' and the class 'MvcApplication' don't match.  We've tried to put a supress list for 'Global.asax.cs' in the sylecop settings but this didn't seem to work. (Currently our work around is to disable the rule entirely but we don't want to keep that as the case, we only want the exception for Global.asax.cs files.)

A: Use a namespace level suppression:
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1649:FileHeaderFileNameDocumentationMustMatchTypeName", Justification = "Reviewed.")]

namespace MyNamespace
{

}

A: Found it out with a bit of time and manipulation of the original tool generated file.
<StyleCopSettings Version="105">
  <Analyzers>
  ... Removed for brevity ...
  </Analyzers>
  <SourceFileList>
        <SourceFile>Global.asax.cs</SourceFile>
        <Settings>
            <Analyzers>
                <Analyzer AnalyzerId="StyleCop.CSharp.DocumentationRules">
                    <Rules>
                        <Rule Name="FileHeaderFileNameDocumentationMustMatchTypeName">
                          <RuleSettings>
                            <BooleanProperty Name="Enabled">False</BooleanProperty>
                          </RuleSettings>
                        </Rule>
                    </Rules>
                </Analyzer>
            </Analyzers>
        </Settings>
    </SourceFileList>
</StyleCopSettings>

Hope this helps out anyone else with this issue.


text:
Q: Text inserted in the edittext is overwritten I'm a beginner and am making a calculator (fairly easy), but it's happening the following problem: When Cline in "1" button for example, he enters this number in the EditText, but if you click again the number is overwritten instead of the inserted his side as desired. How do the numbers were placed side by side without overwriting those already there?
Note: The layout of buttons and etc. I did in. XML, so I'm not using the keyboard native Android.
Thanks!

A: when you want to add a new number next to the old one, you probably need to

*

*get the value that is currently being shown in this "edit text" and save it in a string

*concatenate this old value with the new one that you want to add to your "edit text"

*set this new concatenated value as the new text in your "edit text"

:)


text:
Q: How to calculate energy output using non-tracking CECMods I'm trying to calculate energy output using the pvlib library on CECMod photovoltaic modules. The only implementation I've found (Thanks to Mark and Cliff) assumes that the modules are mounted on a single-axis tracker that follows the sun throughout the day. This is an issue for me since my modules will be fixed and won't track the sun.
Is there a way to calculate the energy output of CECMod modules without assuming that they'll track the sun?
For reference, I've included the implementation using the single-axis tracker below.
import pvlib
import pandas as pd

YEAR = 1990
STARTDATE = '%d-01-01T00:00:00' % YEAR
ENDDATE = '%d-12-31T23:59:59' % YEAR
TIMES = pd.date_range(start=STARTDATE, end=ENDDATE, freq='H')
INVERTERS = pvlib.pvsystem.retrieve_sam('CECInverter')
INVERTER_10K = INVERTERS['SMA_America__SB10000TL_US__240V_']
CECMODS = pvlib.pvsystem.retrieve_sam('CECMod')
CECMOD_POLY = CECMODS['Canadian_Solar_Inc__CS6X_300P']
CECMOD_MONO = CECMODS['Canadian_Solar_Inc__CS6X_300M']
LATITUDE, LONGITUDE = 40.5137, -108.5449
NREL_API_KEY = os.getenv('NREL_API_KEY', 'DEMO_KEY')
EMAIL = os.getenv('EMAIL', 'bwana...@yahoo.com')

header, data = pvlib.iotools.get_psm3(LATITUDE, LONGITUDE, NREL_API_KEY, EMAIL)
# get solar position
data.index = TIMES
sp = pvlib.solarposition.get_solarposition(
        TIMES, LATITUDE, LONGITUDE)
solar_zenith = sp.apparent_zenith.values
solar_azimuth = sp.azimuth.values
dni = data.DNI.values
ghi = data.GHI.values
dhi = data.DHI.values
surface_albedo = data['Surface Albedo'].values
temp_air = data.Temperature.values
dni_extra = pvlib.irradiance.get_extra_radiation(TIMES).values

## Here is where the single-axis tracker is introduced

tracker = pvlib.tracking.singleaxis(solar_zenith, solar_azimuth)
surface_tilt = tracker['surface_tilt']
surface_azimuth = tracker['surface_azimuth']
poa_sky_diffuse = pvlib.irradiance.get_sky_diffuse(
        surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,
        dni, ghi, dhi, dni_extra=dni_extra, model='haydavies')
aoi = tracker['aoi']
poa_ground_diffuse = pvlib.irradiance.get_ground_diffuse(
        surface_tilt, ghi, albedo=surface_albedo)
poa = pvlib.irradiance.poa_components(
        aoi, dni, poa_sky_diffuse, poa_ground_diffuse)
poa_direct = poa['poa_direct']
poa_diffuse = poa['poa_diffuse']
poa_global = poa['poa_global']
iam = pvlib.iam.ashrae(aoi)
effective_irradiance = poa_direct*iam + poa_diffuse
temp_cell = pvlib.temperature.pvsyst_cell(poa_global, temp_air)

# this is the magic
cecparams = pvlib.pvsystem.calcparams_cec(
        effective_irradiance, temp_cell,
        CECMOD_MONO.alpha_sc, CECMOD_MONO.a_ref,
        CECMOD_MONO.I_L_ref, CECMOD_MONO.I_o_ref,
        CECMOD_MONO.R_sh_ref, CECMOD_MONO.R_s, CECMOD_MONO.Adjust)
mpp = pvlib.pvsystem.max_power_point(*cecparams, method='newton')
mpp = pd.DataFrame(mpp, index=TIMES)
Edaily = mpp.p_mp.resample('D').sum() ```

Thanks for any help you can offer!

A: It appears to me that if you create a basic system using the PVSystem class constructor, as opposed to SingleAxisTracker, you can implement basically the same behavior without the tracking feature.
Here is my code that illustrates the implementation of two similar systems with these two constructors, loosely based on the PV production example.
import datetime
import pytz

import pandas as pd
import matplotlib.pyplot as plt

import pvlib.forecast as pvlib_foreacst
import pvlib.pvsystem as pvlib_pvsystem
import pvlib.temperature as pvlib_temperature
import pvlib.tracking as pvlib_tracking
import pvlib.modelchain as pvlib_modelchain

def pv_power_forecast_example():

    """ an example from https://pvlib-python.readthedocs.io/en/stable/forecasts.html?highlight=power#pv-power-forecast """

    sandia_modules = pvlib_pvsystem.retrieve_sam(name="sandiamod", path=None)  # retrieve a table of pv panel data from database name in ["CECMod", "SandiaMod"]
    cec_inverters = pvlib_pvsystem.retrieve_sam(name="cecinverter", path=None)  # retrieve a table of inverter data from database name in ["CECInverter", "SandiaInverter", "ADRInverter"]
    module_parameters = sandia_modules["Canadian_Solar_CS5P_220M___2009_"]  # select single PV module parameters
    inverter_parameters = cec_inverters["SMA_America__SC630CP_US__with_ABB_EcoDry_Ultra_transformer_"]  # select single inverter module paramters
    temperature_modeling_methodology = pvlib_temperature.TEMPERATURE_MODEL_PARAMETERS["sapm"]  # select corresponding cell temperature modelling methodlogy
    temperature_model_parameters = temperature_modeling_methodology["open_rack_glass_glass"]  # select type from  ['open_rack_glass_glass', 'close_mount_glass_glass', 'open_rack_glass_polymer', 'insulated_back_glass_polymer']

    # create a PV system from previous selection

    fig = plt.figure()

    for iterator in [0, 1]:

        if iterator == 0:
            # tracking example
            example_label = "tracking"
            system = pvlib_tracking.SingleAxisTracker(
                axis_tilt=0,  # tilt of rotational axis (axis_azimuth) with respect to horizontal
                axis_azimuth=0,   # east of north
                max_angle=90,
                module_parameters=module_parameters,
                inverter_parameters=inverter_parameters,
                temperature_model_parameters=temperature_model_parameters,
                modules_per_string=15,  # num of modules in series
                strings_per_inverter=300,  # num of modules in parallel
                albedo=0.3,
                surface_type="concrete",
                )

        if iterator == 1:
            # fixed example
            example_label = "fixed?"
            system = pvlib_pvsystem.PVSystem(
                surface_tilt=0,  # surface facing up = 0, surface facing horizon = 90
                surface_azimuth=180,  # N=0, E=90, S=180, W=270
                albedo=0.3,
                surface_type="concrete",
                module=None,  # model name of selected module
                module_type=None,  # [=None, "glass_polymer", "glass_glass"]
                module_parameters=module_parameters,
                temperature_model_parameters=temperature_model_parameters,
                modules_per_string=15,  # num of modules in series
                strings_per_inverter=300,  # num of modules in parallel
                inverter=None,  # model name of selected inverter
                inverter_parameters=inverter_parameters,
                racking_model=None,  # [=None, "open_rack", "close_mount", "insulated_back"]
                losses_parameters=None,
                name=None
                )

        # define test site location and simulation time span
        (latitude, longitude, zone) = (44.787197, 20.457273, "Europe/Belgrade")
        start = pytz.timezone(zone=zone).localize(dt=datetime.datetime(2021, 1, 1, 0, 0)).astimezone(tz=pytz.timezone(zone))
        end = start + pd.Timedelta(days=21)

        model = pvlib_foreacst.GFS(resolution="half", set_type="best")  # instantiate weather data/forecast model
        weather = model.get_processed_data(latitude=latitude, longitude=longitude, start=start, end=end)  # obtain and process weather data/forecast

        model_chain = pvlib_modelchain.ModelChain(system=system, location=model.location)  # create a helper-model i.e. model chain to automate simulation
        model_chain.run_model(weather=weather)  # run the simulation

        plt.plot(model_chain.ac.fillna(0)/1000, label=example_label)
        plt.legend()
        plt.ylabel("AC Power [kW]")
        plt.grid(which="both")
        plt.tight_layout()

        print(example_label + " " + str(model_chain.ac.fillna(0)))
        print("")

    plt.show()
    plt.ion()

    pass

if __name__ == "__main__":
    pv_power_forecast_example()
    pass
else:
    pass

Here is how the results turned out...
However, I have been experimenting with pvlib only for a short time, so do take my response with a grain of salt.