text:
Q: ¿Por qué no funcionan modulos en VueJs?, mapGetter "unknown getter:" Estoy teniendo problemas con con los getters en VueJS. Tengo que cambiar mi barra de navegación dependiendo si el usuario está o no autenticado. Pero me muestra el siguiente error:

[vuex] unknown getter: user/is_authenticated

*

*Store.js

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

// import getters from './getters'
import user from './modules/user'
import front from './modules/front'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    front,
    user
  },

2.user.js
const UserModule = {
  state: {
    is_authenticated: false,
    access_token: null,
    id_token: null,
    email: null,
    name: null,
    lastname: null,
    birth_date: null,
    genre: null,
    document_type: null,
    document_number: null,
    nationality: null,
    country_residence: null,
    phone: null
  },
  getters: {
    is_authenticated: state => state.is_authenticated,
  },
...
export default {
  UserModule,
  namespaced: true
}

3 NavBar.vue
computed: {
    ...mapGetters(['windowsWidth', 'sizes']),
    ...mapGetters('user', ['is_authenticated'])
  },
  mounted () {
    this.menu = routesMenu('portal')
    console.log(this.is_authenticated)
  },

El console.log me da undefined , y al hacerlo sin el nombre del modulo ...mapGetters(['is_authenticated']) , me devuelve false sin importar que valor le de.
Llevo poco tiempo usando Vue, ya he buscado de todo

A: Desde user.js estas exportando una constante que tiene el estado, getters, acciones y mutacacion, pero cuando llamas a ese modulo no tienes la estructura correcta.
una opcion es crear cada variable como una constante y exportarlas de forma individual, que es lo mas comun:
const state = {
    is_authenticated: false,
    access_token: null,
    id_token: null,
    email: null,
    name: null,
    lastname: null,
    birth_date: null,
    genre: null,
    document_type: null,
    document_number: null,
    nationality: null,
    country_residence: null,
    phone: null
  },
  getters = {
   is_authenticated: state => state.is_authenticated,
  },
...

export default {
  state, getters, actions, mutations
  namespaced: true
}

de esta manera accedes a los datos que necesites del modulo.
la otra opcion, que no probe, pero imagino que podria funcionar es editar el mapGetter a algo como:
...mapGetters('user', ['UserModule.is_authenticated'])

insisto en que no lo probe, y es probable que no funcione.


text:
Q: iOS: Getting current WiFi SSID is always nil on Testflight Below is the code I use to get my current WiFi SSID and display it in my app.
I have location permissions set to always, as well as the required Privacy info.plist values. I also have the Access WiFi Information capability added to my project. When I build the app from Xcode to my iPhone (not simulator), it works fine, I can see my WiFi SSID. However, when I distribute the app through Testflight it no longer works, it is returning nothing.
import SystemConfiguration.CaptiveNetwork

private func getWiFiSsid() -> String? {
        var ssid: String?
        if let interfaces = CNCopySupportedInterfaces() as NSArray? {
            for interface in interfaces {
                if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
                    ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
                    break
                }
            }
        }
        return ssid
    }

Below is a screenshot of the entitlements that I unpackages from the ipa file, showing that I do have the Access WiFi Information set:

A: Since CNCopyCurrentNetworkInfo is deprecated from iOS 14 (https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo) consider migrating to NEHotspotNetwork.fetchCurrent and we can use this method with user's authorization to access precise location e.g.:
import CoreLocation
import NetworkExtension

var locationManager: CLLocationManager?

...

locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestAlwaysAuthorization()

...

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedAlways || status == .authorizedWhenInUse {
        NEHotspotNetwork.fetchCurrent { hotspotNetwork in
            if let ssid = hotspotNetwork?.ssid {
                print(ssid)
            }
        }
    }
}

NOTE: you have to set Access WiFi Information to YES in your entitlements file ,Privacy - Location Always and When In Use Usage Description and Privacy - Location When In Use Usage Description in you Info.plist as well.

A: While this is not clearly documented. You don't need the special entitlement from NEHotspotHelper. You need:

*

*Access WiFi Information = YES (in entitlements, either add it manually or via xcode Signing and Capabilities of your target)

*Privacy - Location Always and When In Use Usage Description (in Info.plist)

*Privacy - Location When In Use Usage Description (in Info.plist)

*Location access granted via

*

*
locationManager = CLLocationManager()
locationManager?.requestAlwaysAuthorization()

redpajama_set_name: RedPajamaStackExchange


text:
Q: R Merge multiple vectors alternatively I have 3 vectors
x<- 1:3
y<- 4:6
z<- 7:9

I want to do combine these three vectors into single vector k such that
k
[1] 1,4,7,2,5,8,3,6,9

I did this
k<-c()
for(i in 1:length(x)){
  l<-c(x[i],y[i],z[i])
  k<-c(k,l)
}

I want to avoid loops. Does anyone know how to do this without using a loop?
Thanks

A: We can rbind the vectors to a matrix and convert it to a vector with c
c(rbind(x,y,z))
#[1] 1 4 7 2 5 8 3 6 9


text:
Q: SVG Commands to an array of points in python for plotting I have SVG commands printed out in this style:
M 17.674207527416044,-2.0071468002689765
L 18.71594797636461,-2.1235197095441456
C 18.826423339069347,-2.1286537329883464 19.15862036824475,-2.1295142834870036 19.714241351132454,-2.0062766509553485 20.37767811352802,-1.85633105768394 21.328536750145904,-1.5307796874983068 22.48762758994496,-0.8307488372990495
A 22.5,22.5 0 0,1 22.48762758994496,0.8307488372990495
C 21.328536750145904,1.5307796874983068 20.37767811352802,1.85633105768394 19.714241351132454,2.0062766509553485 19.15862036824475,2.1295142834870036 18.826423339069347,2.1286537329883464 18.71594797636461,2.1235197095441456
L 17.674207527416044,2.0071468002689765
A 0.9375,0.9375 0 0,0 16.643970594477892,2.7827805968410724
A 16.875,16.875 0 0,1 16.44194780227596,3.798417758387414
A 0.9375,0.9375 0 0,0 17.096940414724138,4.909264553410452
L 18.10391707805257,5.200406815029517
C 18.20794771021571,5.237940686841614 18.515187064650465,5.3642719411955415 18.98135291836046

How do I convert this into an image and also be able to generate intermediate points/an array of points, so I can create a 2d plot in python?
Thanks for helping.

A: You can try this python package svgpath2mplhttps://github.com/nvictus/svgpath2mpl. It can convert the SVG path to a matplotlib object.


text:
Q: ASP.Net MVC Cookies Best Practices I'm looking for some guidance with respect to cookies in ASP.Net MVC (or just cookie handling in general). I have been storing authentication information about users who authenticate via a form login in a cookie. This is working great, but I now need to store a little more information in the cookie. This additional information is not really "authentication related" so I'm hesitant to store it in the authentication ticket. Is there a better practice for storing extra information. Is it possible to set multiple cookies (and if so is that a good/bad practice)? Other things I should be considering here?
Here is the current code I'm using to set the authentication ticket and wrap it in a cookie:
private HttpCookie GetAuthCookie(AuthToken authToken)
{
    var authTokenXml = serializationService.Serialize(authToken);
    var authCookieString = FormsAuthentication.Encrypt(
        new FormsAuthenticationTicket(
            0,
            Keys.AuthToken,
            DateTime.Now,
            DateTime.Now.AddMinutes(AppSettings.SessionTimeoutMinutes),
            true,
            authTokenXml));
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, authCookieString)
                     {
                         Expires = DateTime.Now.AddDays(AppSettings.AuthCookieExpireDays)
                     };
    return cookie;
}

A: There is a size limit to how big a cookie can be, 4096 bytes. After this, you may need to chunk the data into several cookies if wanting to continue to store in cookies. Obviously you now have the added complexity of reading from all to reconstruct your authentication ticket + data and, if one cookie was not sent with the rest, it may have some dire consequences.
Have you looked at using a different session store? That's effectively what you're using the cookie as here and unless it's related to authentication and needs to be available in the processing pipeline before session is accessible, I'd be inclined to look at putting this in session. You could use an out of process session store such as a database if not wanting to store session in process.

A: Rule of thumb: store in the cookie only the minimum (usually this is the user id) and use this minimum to fetch the rest from your datastore every time you need it. If you are happy with the performance you can stop reading.
If you realize that there are too many queries to your datastore you could use session or cache the results of your queries.

A: You should not put anything but authentication data in authentication cookie.
Asp.net usage of cookies is much the same as in any programming platform for web.
You can set as many cookies as you like and store in them whatever you want.
Some examples:
http://www.cookiecentral.com/faq/
http://stephenwalther.com/blog/archive/2008/07/08/asp-net-mvc-tip-15-pass-browser-cookies-and-server-variables-as-action-parameters.aspx
http://www.asp.net/general/videos/read-write-and-delete-cookies-in-aspnet


text:
Q: Yarn 2 logfilters for Default Steps In Yarn 2 I am using logFilters to hide some logs. This works for warnings, but I would like to hide the default messages, such as Resolution step etc as well. Except for Done.

How can I achieve that? Please find my .yarnrc.yml code below:
logFilters:
  - code: "YN0002"
    level: discard
  - code: "YN0060"
    level: discard
  - text: "Resolution step"
    level: discard
  - text: "Fetch step"
    level: discard
  - text: "Link step"
    level: discard
  - pattern: "*Completed in *"
    level: discard


text:
Q: Return values from private void radioButton_CheckedChanged(object sender, EventArgs e) How do I change the following class/method to accept global variables and also return a value?
private void radioButton_CheckedChanged(object sender, EventArgs e)

Ideally, I want it to return either a string or a text. But that doesn't happen just by changing void to int or string and using return command inside it. Making the same public also doesn't seem to work.
Any inputs or suggestions, please?
---------------------EDIT-ADDED-LATER---------------------
What I am trying to do was for this - C# - How do I separately return int values from each radio GroupBox?

A: I am afraid, what you're saying is not possible to be achieved.
This is an event handler and the event is raised internally when the checked state of your radio button is changed.
The signature and return method is decided my Microsoft obviously and you cannot change the arguments of return type of event handlers.
Also returning a data type to a radio button doesn't sound too good, and you never need that. I think your requirement might be to change some properties or controls that is existing in the UI. That could be easily done from within the event handler and doesn't require you to modify them.
Hence there is no need for changing their signature. If you could tell more about your requirement, we could suggest a solution based on that.

A: Based on another thread, where some suggestion was made, I found that I am able to get this via the following way.
int value = 0;
protected void radioButton_CheckedChanged(object sender, EventArgs e)
if (radioButton.Checked)
   {
       value = 100;
   }

Can somebody review and tell whether any mistakes are there in this? It does what I want, but at what cost?


text:
Q: String and index in Swift 3 here's a part of my code :
let separator = anyWord.indexOf("-")!
if (separator >= 0) {
let res = anyWord[anyWord.characters.index(after: separator)..<anyWord.endIndex] //get an error
//some code
}

I get an error in 'let res' part - Type 'String!' has no subscript members
if I do  :
let separator = anyWord.indexOf("-")!
let subStartIndex = anyWord.characters.index(after: separator)

the extension to String :
extension String {
    public func indexOf(_ char: Character) -> Int! {
        if let idx = self.characters.index(of: char) {
            return self.characters.distance(from: self.startIndex, to: idx)
        }
        return Const.INVALID_VALUE
    }

I get error :

String may not be indexed with 'Int", it has variable size elements

A: You are thinking too complicated, it's pretty easy in Swift 3 using range(of and upperBound
let anyWord = "asdghf-fkgjh"
if let separator = anyWord.range(of:"-") {
   let res = anyWord.substring(from: separator.upperBound)
   //some code
}

A: Cast it to string
let test: String
test = "Test-Word"
if let separatorWord = anyWord.range(of: "-")
{
let word = anyWord.substring(from: anyWord.index(after:
separatorWord.lowerBound))
print(word)
}

A: I like 'pure' swift solution ( no Foundation required )
let anyWord = "asdghf-fkgjh-blablabla--bla"
anyWord.characters.split(separator: "-").forEach { print( String($0)) }

it prints
asdghf
fkgjh
blablabla
bla


text:
Q: How to prevent window to be clickable/do actions on it in javafx? I have a javafx application and at a certain point I show a Popup this way:
public static void newWind(String fxml) throws IOException{

            FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
            Parent root1 = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.setTitle("ABC");
            Scene newscene = new Scene(root1);
            newscene.getRoot().setStyle("-fx-font-family: 'Arial'");
            stage.setScene(newscene);
            stage.show();

    }

The thing is that I want that the user can't click or do anything in the background non-popup window until he completes the operation in the popup. I want, basically, to "freeze" the old background window...


text:
Q: Spring 2.5 + quartz java.lang.NoClassDefFoundError: org/quartz/JobDetail I have an issue with quartz library. I'm using it with spring 2.5:
<bean id="reminderBean" class="com.mail.timexis.ReminderBean">
        <property name="mailSender">
            <ref local="timexisMailSender" />
        </property>
    </bean>

    <bean id="jobDetail"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="reminderBean" />
        <property name="targetMethod" value="execute" />
    </bean>

    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="jobDetail" />
        <!-- run every morning at 6 AM -->
        <property name="cronExpression" value="* * * * * ?" />
    </bean>

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="cronTrigger" />
            </list>
        </property>
    </bean>

Maven:
<dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>1.8.4</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2</version>
        </dependency>

And when i run tomcat it cannot instantiate "jobDetail" bean because it can't see JobDetail class used by MethodInvokingJobDetailFactoryBean class ( Caused by: java.lang.NoClassDefFoundError: org/quartz/JobDetail)
Maven downloads the jars and i can see it under MavenDependencies and I can find the JobDetail class.
I think it's something with the compatibility of spring 2.5 and quartz. Any ideas?

A: Did you add the dependency to spring-context-support ?
It contains the org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean which seems to be missing according to the stacktrace.


text:
Q: Laravel - Fail update model with many-to-many when using FormRequest validation I would need some help understanding what I am doing wrong.
I have really basic 'required' fields defined in a PostUpdateRequest rules method.
Then, my update method in PostController:
public function update(PostUpdateRequest $request, Post $post)
{
    $post->update($request->validated());
    $post->tags()->sync(request('tags'));
    return redirect() ...
}

When I use the method without validation, it works:
public function update(Request $request, Post $post)
{
    $post->update($request->all());
    $post->tags()->sync(request('tags'));
    return redirect() ...
}

I am not connecting the dots here ... I even have the store method that is working perfectly with FormValidation:
public function store(PostStoreRequest $request, Post $post)
{
    $post = Post::create($request->validated());
    $post->tags()->attach(request('tags'));
    return redirect() ...
}

My guess ... it's a validation thing ... the request never hits the controller action


text:
Q: How do I split a string into 2 parts based on a delimiter? I have table in a SQL Server database with the following columns:
Field1, Field2, Field3

Field1 is a column of type string with '|' as a separator.
It has the following form:
Part1|Part2

I'd like to write a SQL query which returns the following columns:
Part1, Part2, Field2, Field3

What is the best way to do that?

A: One option here is to make use of SQL Server's base string functions SUBSTRING() and CHARINDEX() to split apart the two parts of Field1 on the pipe character.
SELECT SUBSTRING(Field1, 1, CHARINDEX('|', Field1)-1) AS Part1,
       SUBSTRING(Field1, CHARINDEX('|', Field1)+1, LEN(Field1)) AS Part2,
       Field2,
       Field3
FROM yourTable

A: The advantage of this approach(besides being short), is that it will not fail, if the pipe is missing.
SELECT
  SUBSTRING(Field1, 0, charindex('|',Field1)) Part1,
  STUFF(Field1,1,charindex('|',Field1),'') Part2,
  Field2,
  Field3
FROM (values('abc|def','val2','val3')) x(Field1, field2, Field3)

A: Let me start by saing I totally agree with Marc_s's comment - Never ever store multiple values in a single column.
For more information, read Is storing a delimited list in a database column really that bad?, where you will see a lot of reasons why the answer to this question is Absolutly yes!
Now, assuming you can't change the database structure, here is one way to do it using Left and Right with charIndex
Create and populate sample table (Please save us this step in your future questions)
DECLARE @T AS TABLE
(
    Col varchar(10)
)

INSERT INTO @T VALUES
('a|b'),
('ab|cd'),
('abc|def'),
('abcd|efgh'),
('abcde|fghi')

The Query:
SELECT  Col,
        LEFT(Col, CHARINDEX('|', Col)-1) As Part1,
        RIGHT(Col, LEN(Col) - CHARINDEX('|', Col)) As Part2
FROM @T

Results:
Col             Part1   Part2
a|b             a       b
ab|cd           ab      cd
abc|def         abc     def
abcd|efgh       abcd    efgh
abcde|fghi      abcde   fghi

A: Here is a simple function that could be used to split string in DB:
SELECT value FROM STRING_SPLIT('Lorem ipsum dolor sit amet.', ' ');

it will return all the values by splitting with space.


text:
Q: Custom post type not displaying content from single-{custom post type} page I am trying to create a custom post type with taxonomy and a shortcode for my custom search in a plugin.When I activate my plugin I see my CPT and taxonomy on dashboard. But when I publish the post I do not see the data in form of the single-{CPT}.php page I created. Instead, it displays list of all posts from my CPT. The relevent files are as below.
index.php (my plugin page)
function register_vfic_post_type() {

    /* ----Begin Code to include Custom Post Types and its Taxonomies----- */

        register_post_type('vfic_publications', array(  'label' => 'VFIC Publications','description' => '','public' => true,'show_ui' => true,'show_in_menu' => true,'capability_type' => 'post','hierarchical' => false,'rewrite' => array('slug' => ''),'query_var' => true,'exclude_from_search' => false,'supports' => array('title','editor','excerpt','revisions','author','page-attributes',),'labels' => array (
          'name' => 'VFIC Publications',
          'singular_name' => '',
          'menu_name' => 'VFIC Publications',
          'add_new' => 'Add VFIC Publications',
          'add_new_item' => 'Add New VFIC Publications',
          'edit' => 'Edit',
          'edit_item' => 'Edit VFIC Publications',
          'new_item' => 'New VFIC Publications',
          'view' => 'View VFIC Publications',
          'view_item' => 'View VFIC Publications',
          'search_items' => 'Search VFIC Publications',
          'not_found' => 'No VFIC Publications Found',
          'not_found_in_trash' => 'No VFIC Publications Found in Trash',
          'parent' => 'Parent VFIC Publications',
        ),) );
        flush_rewrite_rules();
    }
    add_action( 'init', 'register_vfic_post_type' );

    register_taxonomy('Year',array (
        0 => 'vfic_publications',
        ),array( 'hierarchical' => false, 'label' => 'Year','show_ui' => true,'query_var' => true,'rewrite' => false,'singular_label' => 'Year') );

    register_taxonomy('PubsAuthor',array (
        0 => 'vfic_publications',
        ),array( 'hierarchical' => false, 'label' => 'PubsAuthor','show_ui' => true,'query_var' => true,'rewrite' => false,'singular_label' => 'PubsAuthor') );

    register_taxonomy('Journal',array (
        0 => 'vfic_publications',
        ),array( 'hierarchical' => false, 'label' => 'Journal','show_ui' => true,'query_var' => true,'rewrite' => false,'singular_label' => 'Journal') );

    register_taxonomy('nts',array (
        0 => 'vfic_publications',
        ),array( 'hierarchical' => false, 'label' => 'Non-Technical Summary','show_ui' => true,'query_var' => true,'rewrite' => false,'singular_label' => 'nts') );

    function vfic_ctg_rewrite_flush() {
        register_vfic_post_type();
        flush_rewrite_rules();
    }
register_activation_hook( __FILE__, 'vfic_ctg_rewrite_flush' );

/* ----END Code to include Custom Post Types and its Taxonomies----- */

function vfic_pubs_forms_shortcode() { ?>

    <form role="search" method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">

Keyword(s): <input type="text" class="field" name="s" value="" id="s" class="s" />
        <input type="checkbox" name="abstract" value=""/>Just Search Abstract

Author(s): &nbsp&nbsp <?php $myterms = get_terms(array('PubsAuthor'), array('order'=>'ASC','hide_empty'=>true));
                $author = "pubsauthors";
                $emptyvalue = "";
                $text = "text";
                    $term_taxonomy=$term->PubsAuthor;
                    $term_slug=$term->slug;
                    $term_name =$term->name;
                    $link = $term_slug;
                    $output .="<input type='".$text."' name='".$link."'/>";

                echo $output; ?>
                    <?php $myterms = get_terms(array('PubsAuthor'), array('order'=>'ASC','hide_empty'=>true));
                $author = "pubsauthor";
                $emptyvalue = "";
                $output ="<select name='".$author."'><option selected='".$selected."' value='".$emptyvalue."'>--Select Authors--</option>'";

                foreach($myterms as $term){
                    $term_taxonomy=$term->PubsAuthor;
                    $term_slug=$term->slug;
                    $term_name =$term->name;
                    $link = $term_slug;
                    $output .="<option name='".$link."' value='".$link."'>".$term_name."</option>";
                }
            $output .="</select>";
            echo $output;
                    ?>

Year:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
        <?php $myterms = get_terms(array('Year'), array('order'=>'ASC','hide_empty'=>true));
            $year = "pubsyear";
            $emptyvalue = "";
            $output ="<select name='".$year."'><option selected='".$selected."' value='".$emptyvalue."'>--Select Year--</option>'";

            foreach($myterms as $term){
                $term_taxonomy=$term->Year;
                $term_slug=$term->slug;
                $term_name =$term->name;
                $link = $term_slug;
                $output .="<option name='".$link."' value='".$link."'>".$term_name."</option>";
            }
            $output .="</select>";
            echo $output;
        ?>

        <input type="hidden" name="post_type" value="vfic_publications" />
        <input type="submit" id="submit" value="Search" />
    </form>

<?php } ?>
<?php add_shortcode('vfic_pubs_search', 'vfic_pubs_forms_shortcode');
add_filter( "template_redirect", "get_custom_post_type_template" ) ;?>
<?php function get_custom_post_type_template($template_redirect) {
         global $post;

         if ($post->post_type == 'vfic_publications') {
              $template_redirect = get_template_part('loop','vfic_publications');
         }
         return $template_redirect;
    } ?>

loop-{custom post type}.php page
get_header(); ?>
<?php
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();

foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach

$search = new WP_Query($search_query);
$author = $_GET['pubsauthor'];
$abstract = $_GET['abstract'];

$tax_query = array('relation' => 'OR');
if ($_GET['pubsauthor'])
{
    $tax_query[] =  array(
            'taxonomy' => 'PubsAuthor',
            'field' => 'slug',
            'terms' => array($_GET['pubsauthor'])
        );
}
if ($_GET['pubsyear'])
{
    $tax_query[] =  array(
            'taxonomy' => 'Year',
            'field' => 'slug',
            'terms' => array($_GET['pubsyear'])
        );
}

$query = new WP_Query(
array(
    //Retreive ALL publications posts
    'post_type' => 'vfic_publications',
    'posts_per_page' => '-1',
    'tax_query' => $tax_query
)
);

?>

<?php if ( $query->have_posts() ) : ?>

Your search returned<?php /* Search Count */ $allsearch = &new      WP_Query(array(
    //Retreive ALL publications posts
    'post_type' => 'vfic_publications',
    'posts_per_page' => '-1',
    'tax_query' => $tax_query
    )); $key = wp_specialchars($s, 1); $count = $allsearch->post_count;   _e(''); _e(''); echo $key; _e(''); _e(' — '); echo $count . ' '; _e('result(s)'); wp_reset_query(); ?>

Please contact individual journals to obtain a full copy of the publication.

<?php while ( $query->have_posts() ) : $query->the_post(); ?>

<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'agriflex' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?>

<?php endwhile; // End the loop. Whew. ?>

<?php elseif ( have_posts() ) : ?>

....<?php printf( __( 'Search %s', 'agriflex' ), '' . get_search_query() . '' ); ?>

            <?php
            /* Run the loop for the search to output the results.
             * If you want to overload this in a child theme then include a file
             * called loop-search.php and that will be used instead.
             */
             get_template_part( 'loop', 'search' );
            ?>

<?php else : ?>

<?php _e( 'Nothing Found', 'agriflex' ); ?>

<?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'agriflex' ); ?>

                    <?php get_search_form(); ?>

<?php endif; ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Any help with this is really appreciated.

A: You need to rename loop-{custom-post-type}.php to single-{custom-post-type}.php.
And to be explicit, the actual filename, based on your code above, should be:
single-vfic_publications.php.
Get rid of any other template redirects or anything else similar that you're using. As per the Template Hierarchy, if you have a Custom Post Type named vfic_publications, and a template file named single-vfic_publications.php, WordPress will automatically use it to render the single-post view for that CPT.
The other issue that's going on here is that you appear to be trying to use the single post view page as an archive index page. You don't need to do that. Instead, create a archive-vfic_publications.php file, and WordPress will automatically use it to render the archive-index page view for your CPT.
You also appear to be doing tax queries in your template file. You might want to consider instead using taxonomy template files for that purpose.

A: You use the following code:
add_filter( "template_redirect", "get_custom_post_type_template" ) ;?>
<?php function get_custom_post_type_template($template_redirect) {
         global $post;

         if ($post->post_type == 'vfic_publications') {
              $template_redirect = get_template_part('loop','vfic_publications');
         }
         return $template_redirect;
    } ?>

But it's not clear why you would do such a thing. If you're trying to load loop-vfic_publications.php get_template_part won't work unless that file is in the theme.
If it is in the theme, then this function is a waste, and you should use the file single-vfic_publications.php instead with a get_template_part() to include the loop file.

A: The get_template_part function is used to include a template file, not return the file path, which is expected.
I would change your line:
$template_redirect = get_template_part('loop','vfic_publications');

to
$templates = array( 'loop-vfic_publications.php', 'loop.php' );
$template_redirect = locate_template( $templates, false, false );


text:
Q: No JQuery intellisense in cshtml files in Visual Studio 2022 After several hours I can't figure out how to get intellisense working when using JQuery in .csthml files. From what i've read on other posts etc. it should be possible.
My current setup:

*

*Visual Studio 2022

*ASP.Net Core 7 MVC

I can confirm JQuery is working just fine when running the project.
Any help is appreciated.
Thanks.

A: Here is a solution from Microsoft, Hope it can give you some help:

Starting in Visual Studio 2022, for performance reasons, we no longer
automatically analyze all JavaScript files in your project unless you
explicitly opt in. You can do this by unchecking "Ignore Source Files
From VisualStudio Projects" under Tools->Options->Text
Editor->JavaScript/TypeScript->Project->General, or by adding a
tsconfig.json/jsconfig.json file to your project.

Refer to this link.


text:
Q: Java issue with regular expression I am having a bit of trouble with the following code:
^([0-9]{17})\.zip$

I thought that this should stop any strings which has any more than 17 characters from passing through. However, it is allowing files with names over 17 characters to pass through.
Any idea what could be the issue or if my notation is wrong?
Thanks in advance

A: Your regular expression will match a filename consisting of exactly 17 digits (0 to 9) ending with ".zip". If your code is allowing longer filenames through, then it's likely to be the fault of the code that uses it, not the regex itself. Can you post some of your code as well?

A: You need to convert the expression to:
^([0-9a-zA-Z]{,17})\.zip$

Otherwise it considers only numbers.

A: Your regex only allows file names of exactly 21 characters: 17 digits, 1 dot then "zip".
One way to limit it to 17 is:
^([0-9]{13})\.zip$

A: Given that you want to allow any String under 17 characters, you should probably be using ".", which matches any character rather than just numbers or letters.
Try changing you regex to: ^.{1,17}\.zip$   (Double backslash for escape since this is Java)
@Test
public void testRegexShouldMatch() {
    Pattern pattern = Pattern.compile("^.{1,17}\\.zip$");
    Matcher matcher = pattern.matcher("some file name.zip");
    assertTrue(matcher.find());
}

@Test
public void testRegexShouldNotMatchAsOver17Chars() {
    Pattern pattern = Pattern.compile("^.{1,17}\\.zip$");
    Matcher matcher = pattern.matcher("some long file name.zip");
    assertFalse(matcher.find());
}

A: Your expression would match only exactly 17 digits followed by .zip. If you want to match not only digits but also chracters and relax the constraint to at most 17 digits (and at least 1), you should change your axpression to this:
^([\w]{1,17})\.zip$


text:
Q: WKB for non-homogeneous ODE Consider the ODE $$\epsilon^2 y'' + \epsilon x y' - y = -1, \; y(0) = 0, \; y(1) = 3$$
I've seen the WKB method applied to homogeneous (linear) ODEs, but here we have the $-1$ term. I could perhaps do a change of variable writing $z = -y + 1$, but what if instead I consider the homogeneous case: $\epsilon^2 y'' + \epsilon x y' - y = 0$? Once I get the corresponding WKB solution how then do we obtain the WKB particular solution?

Regarding turning points, does $x = 0$ count as a turning point?

A: Nothing exciting happens. The WKB method provides approximations to basis solutions of the homogeneous ODE. You need to add a particular solution, here $y_p=1$, to the linear combinations of the basis solution to get the inhomogeneous solution.

Just applying the method, without special consideration for the second term at $x=0$, gives for the approximation of an exponential basis solution $y=\exp(S/ϵ)$, $S'=s=s_0+ϵs_1+...$,
\begin{align}
0&=s^2+xs+ϵs'-1\\
(2s_0+x)^2&=4+x^2\\
2s_0s_1+xs_1&=-s_0'=-\frac{x}{2s_0+x}
\end{align}
so in the first two terms $s_0=\frac12(-x\pm\sqrt{4+x^2})$ and $s_1=-\frac{x}{4+x^2}$, which integrates to give
\begin{align}
S_0&=-\frac14x^2\pm\frac14x\sqrt{4+x^2}+\ln(\sqrt{4+x^2}\pm x)
\\
S_1&=-\frac12\ln(4+x^2)
\end{align}
The variant of $S_0$ that gives a bounded solution for $x>0$ is the one with the negative sign. However, as there is no outer solution from these basis solutions, there will also be a boundary layer at $x=1$. The full approximation is thus
$$
y(x)=1-\frac{y_-(x)}{y_-(0)}+2\frac{y_+(x)}{y_+(1)},
$$
where
$$
y_\pm(x)=\frac1{\sqrt{4+x^2}}\exp\left(\frac{\mp\frac{x}4(\sqrt{4+x^2}\pm x)+\ln(\sqrt{4+x^2}\pm x)}{ϵ}\right)
$$


text:
Q: event receiver issue I have made event receiver which updates a field in a list, that event receiver is running in the subsite but not the the root site. The event receiver is scope = web.
Can there be some issue with that, also I cannot see
SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                EventLog.WriteEntry("Windows SharePoint Services 3", errormsg);

            });

Please suggest, The site is in WSS 3
Thanks

A: Download and install Sharepoint Manager http://spm.codeplex.com/releases/view/22762 then browse to your list. See if the event receiver is actually atttached. If not, you have a deployment issue. If yes you have a code issue! :)


text:
Q: Exporting dataframe to csv not showing first column I'm trying to export my df to a .csv file. The df has just two columns of data: the image name (.jpg), and the 'value_counts' of how many times that .jpg name occurs in the 'concat_Xenos.csv' file, i.e:
M116_13331848_13109013329679.jpg    19
M116_13331848_13109013316679.jpg    14
M116_13331848_13109013350679.jpg    12
M116_13331848_13109013332679.jpg    11
etc. etc. etc....

However, whenever I export the df, the .csv file only displayes the 'value_counts' column. How do I modify this?
My code is as follows:
concat_Xenos = r'C:\file_path\concat_Xenos.csv'

df = pd.read_csv(concat_Xenos, header=None, index_col=False)[0]
counts = df.value_counts()

export_csv = counts.to_csv (r'C:\file_path\concat_Xenos_valuecounts.csv', index=None, header=False)

Thanks! If any clarification is needed please ask :)
R

A: This is because the first column is set as index.
Use index=True:
export_csv = counts.to_csv (r'C:\file_path\concat_Xenos_valuecounts.csv', index=True, header=False)

or you can reset your index before exporting.
counts.reset_index(inplace=True)


text:
Q: Legend in Matlab Graph I need to produce a X vs Y graph and make a distinction between positive class and negative class (indicated in original data infile). How do I produce a legend in such a graph? This is my code for the graph right now :
infile = fopen('ClassData1.txt','r');
data = textscan(infile,'%f %f %f');
parameters = [data{1} data{2}];
label = [data{3}];
h = ones(100,9);
g = ones(100,9);
score1= ones(1,9);
sc = 0;
figure
for i = 1:100
        if label(i)>0
            plot(parameters(i,1),parameters(i,2),'r*')
            hold on
        else
            plot(parameters(i,1),parameters(i,2),'b*')
        end
end

A: There are (more than) two ways to do this. Firstly, you can just use a single plot command and do the legend normally, by combining the plot definitions using logical indexing, or you can use the DisplayName property for each plot to give information about the legend.
% Some sample data
parameters=rand(100,2);
label=parameters(:,1)-0.5;

% Use logical indexing to replace the for loop and use a single plot command
figure(1)
plot(parameters(label>0,1),parameters(label>0,2),'r*',parameters(label<=0,1),parameters(label<=0,2),'b*')
legend('red','blue')

% Use DisplayName to set the legend entry for each plot, then show the legend using the names given
figure(2)
plot(parameters(label>0,1),parameters(label>0,2),'r*','DisplayName','Red')
hold on
plot(parameters(label<=0,1),parameters(label<=0,2),'b*','DisplayName','Blue')
hold off
legend('show')

A: To show each line type only once, you have to keep the handles. Storing only one handle per class is sufficient.
h=nan(2,1)
for i = 1:100
    if label(i)>0
        h(1)=plot(parameters(i,1),parameters(i,2),'r*')
        hold on
    else
        h(2)=plot(parameters(i,1),parameters(i,2),'b*')
    end
end
legend(h)


text:
Q: Cut Sound of an Embedded Video I load a swf who contains flv video. I try to modify volume of sound but I don't know how do it...
Is there an netStream with soundtransform ?
Any volume property ?
Any idea ?
Regards,
Mathieu B.

A: The NetStream class does have a soundTransform property and the SoundTransform class does have a volume property.


text:
Q: Flutter/Riverpod: Call method within StateNotifier from another StateNotifier How can I call the method of one StateNotifier from another StateNotifier? I want to call addNewHabit (in the top class) from submitData (in the lower class).
Here are the bodies of the classes:
class HabitStateNotifier extends StateNotifier<List<Habit>> {
  HabitStateNotifier(state) : super(state ?? []);

  void startAddNewHabit(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (_) {
          return NewHabit();
        });
  }

  //this one right here
  void addNewHabit(String title) {
    final newHabit = Habit(title: title);
    state.add(newHabit);
  }

  void deleteHabit(String id) {
    state.removeWhere((habit) => habit.id == id);
  }
}

and
class TitleControllerStateNotifier
    extends StateNotifier<TextEditingController> {
  TitleControllerStateNotifier(state) : super(state);

  void submitData() {
    if (state.text.isEmpty) {
      return;
    } else {
      //call 'addNewHabit' from above class
    }
  }
}

What is the correct way to do this?

A: Technically, not a recommended pattern to use as StateNotifiers are controllers and you shouldn't really be calling controllers inside controllers.
But this is pretty easy to accomplish as you can read other providers inside a provider.
final habitProvider = StateNotifierProvider((ref) => HabitStateNotifier());

final userControllerProvider = StateNotifierProvider((ref) {
  return UserController(

    habitProvider : ref.read(habitProvider),
  );
});

And then use the reference and call
class TitleControllerStateNotifier
    extends StateNotifier<TextEditingController> {
  TitleControllerStateNotifier(state, HabitStateNotifier habitProvider) :
  habit = habitProvider,
  super(state);

  final HabitStateNotifier habit;

  void submitData() {
    if (state.text.isEmpty) {
      return;
    } else {
      habit.addNewHabit(state.text);
    }
  }
}

A: Set up a StateNotifierProvider (from Riverpod), which will give you back a StateNotifier after running the create callback.  This callback has a (ref) parameter on which you can call ref.read and ref.watch to fetch other providers in either non-depending or depending mode.


text:
Q: Зачем задавать переменной тип массив? Иногда встрачаю такие записи:
$arr = array(); // зачем писать эту строку?
$arr = [1,2,3];
print_r($arr);

Ещё где-то краем уха слышал, что от этой первой строчки, как-то снижается нагрузка на проц. Поправьте, если я слышал звон.

A: В вашем примере первая строчка - лишняя и она не дает никакого снижения нагрузки на проц. Наверное, вы видели немного другой вариант использования инициализации массивов:
$arr = [];
$arr[1] = 'one';
print_r($arr);

В таком случае инициализировать массив необходимо ($arr = [] или $arr = array()), так как если переменная $arr была использована где-то еще ранее в коде  ($arr['product_id'] = 321), то в ней могут остаться данные, что может стать сюрпризом при выборке этих данных.

A:
зачем писать эту строку?

В конкретно вашем примере - это делать не нужно. Инициализация "пустой" переменной с определением какого-то типа (string, array, integer) нужно в тех случаях, когда ниже по коду эта переменная будет принимать участие в каких-либо операциях. Например, если вы будете добавлять очередное значение в массив, то этот массив, пусть и пустой, уже должен существовать. Если будем говорить о строках, то тут может идти речь о конкатенации и чтобы "склеить" значения в переменной, в ней уже должна быть хоть какая-то строка. То же самое и числовыми типами и, например, возможных математических операциях.
$arr = [];
// где-то ниже
$arr[] = 'new value';

$str = '';
// где-то ниже
$str .= 'new value';

$int = 0;
// где-то ниже
$int++;

Что касается $arr = [] и $arr = array(), то принципиальной разницы нет. Первый вариант введен, как короткий синтаксис в PHP5.4

A: Для читабельности. В PHP нет способа объявить массив, поэтому иногда так и пишут.
Но ваш пример очень прост. Обычно присвоение непустого массива происходит где-то чуть ниже в коде.


text:
Q: Populate select with javascript array I have two selects in my form : sources and files, everytime a source is chosen , I want to add the source chosen's files in the second select which is for the files
So far I made this:

Select source(s)

<select class="selectpicker" multiple name="source" onchange="getval(this);">
<c:forEach var="source" items="${sources}">
<option value="${source.source_id}">${source.url}</option>
</c:forEach>
</select>

  Select file(s)

 <select class="selectpicker" multiple id="file" name="file">

  </select>

and this is the getVal() function:
 function getval()
 {
 var myList = new Array();

 <c:forEach items="${files}" var="item" varStatus="loop">
    myList["${loop.index}"] = "${item.description}";

     </c:forEach>
    var select = document.getElementById("file");
    for(index in myList) {
   var opt = document.createElement('option');
     option.text =myList[index];
    select.add(option);
    }

  }

A: JSP runs on the server side and the javascript on the client side.
JSP requires a form submit or page reload to act , whereas the effect you want can best be done using javascript, which is run on the client's browser, without interaction with the server.
Use javascript, not JSP for the getVal function; it is fine to use JSP for the initial values of the source dropdown though.
Do also give an id attribute to your "source" select:
function getval()
{
    var opts = document.getElementById("source").options;
    var select = document.getElementById("file");
    // remove previous options in
    for( index in select.options)
       select.remove( index );
    for( index in opts ) {
         if( opts[index].selected )
         {
               var option = document.createElement("option");
               option.value = opts[index].value ;
               option.text = opts[index].text ;
               select.add(option);
         }
    }

}


text:
Q: C static library cannot link with librt I have to create a static library (it is not an option to create a dynamic one), and I have a function in this static library which uses timer_create from time.h e.g. something like this:
somelib.h:
#include <time.h>

int do_something(void);

somelib.c:
int do_something(void){
        timer_t timer;
        struct sigevent sevp;
        sevp.sigev_notify = SIGEV_SIGNAL;
        sevp.sigev_signo = SIGRTMIN;
        sevp.sigev_value.sival_ptr = NULL;
        int ret = timer_create(CLOCK_MONOTONIC, &sevp, &timer);
        timer_delete(timer);
        return 0;
}

The code is actually meaningless and just there to make is necessary to link against librt to illustrate my prolem, which is as follows:
After I compile somelib.c:
gcc -c -o somelib.o somelib.c -lrt

and make the static library:
ar rcs somelib.a somelib.o

I get the following error when linking against it:
gcc -o someexec someexec.c -lrt ./somelib.a

returns:
somelib.c:(.text+0x30): undefined reference to `timer_create'
somelib.c:(.text+0x44): undefined reference to `timer_destroy'

This is a minimum example for my problem. I am not sure though if this can be fixed at all, because my understanding was, that the static lib would have to know the location of librt at the time of its creation and since it is dynamic it is not possible without linking against a static version of librt. Still I don't use static libraries very often, so I would like to know if there is a way to do something like this.
Compiler version: gcc 4.8.1
No other flags set.

A: gcc -c -o somelib.o somelib.c -lrt
That is compilation only, the -lrt is irrelevant here.
gcc -o someexec someexec.c -lrt ./somelib.a
The order in which objects/libraries are given matters.
Try to push -lrt to the end, then it should work.


text:
Q: Sequelize eager Loading check query (ex: it has...?) Project.belongsToMany(User, {through: 'UserProject'});
User.belongsToMany(Project, {through: 'UserProject'});

I want to get Projects have user named 'john'
        include: [
          {
            model: model.User,
            where: { name: 'john' },
          },
        ],

I want result data,
[
    name: 'proejectA',
    Users: [
        { name: 'john' }, { name: 'mike' }, { name: 'dude' } ...
    ]
]

But it gave to me
[
    name: 'proejectA',
    Users: [
        { name: 'john' }
    ]
]

I want Projects with Whole Users, have a user named 'john'.
Is it possible query?

A: You can't achieve that simply, but there is a way you can do that :
For that you have to define one more association with the alias, and one more include :
Project.belongsToMany(User, {through: 'UserProject'});
User.belongsToMany(Project, {through: 'UserProject'});
User.belongsToMany(Project, {through: 'UserProject',as: 'projectUsers'}); // <--- HERE

include: [
    {
        model: model.User,
        where: {
            name: 'john'
        }
    },
    {
        model: model.User,
        as : 'projectUsers'
    }
],

This will produce the result somwthing like this:
[
    name: 'proejectA',
    projectUsers: [
        { name: 'john' }, { name: 'mike' }, { name: 'dude' } ...
    ],
    Users: [
        { name: 'john' }
    ]
]


text:
Q: how to toggle sub menus when user click one menu to other menu when we click on menu C it open sub menus but when we click on B it closes C's sub menus but doesn't open B's sub menus (see fiddle)

A

B

1A

1B

1C

1D

1E

  C

1A

1B

1C

1D

1E

jQuery code here
$('#filter-menu-button-menu').menu({
    "position": {
        my: "right top",
        at: "left top",
        collision: 'flipfit'
    }
});
$('#filter-menu-button-menu').unbind('mouseenter mouseleave');

if two menu B and C is present then click on one should open it's sub menu and close other submenu...how can we do this .
     check this fiddle
http://jsfiddle.net/tAH6a/23/


text:
Q: What's the difference between Thread.yield() and Thread.sleep(0) in Java?
Possible Duplicate:
Are Thread.sleep(0) and Thread.yield() statements equivalent?

In my understanding, both Thread.yield() and Thread.sleep(0) should make the CPU rejudge which thread to run by some scheduling algorithm.
The difference is:

*

*Thread.yield() is to give the executive chance to other threads, but Thread.sleep(0) will not, it'll just tell CPU that you should rearrange the executive threads including the current thread itself.

*Thread.yield() is just an advice which means it may not be accepted at all, but Thread.sleep(0) will do the rearrangement forcedly.
Are the two above conclusions right?

A: Thread.Sleep() has a slightly larger overhead because it creates a system that includes some kind of timer that will wake the process. (Depends on implementation basically)
Bottom line it will call a Yield() in the end.
Thread.Yield() Will just give-up the thread's turn, and gain it in the next round.
Thread.Sleep(0) might have an optimization to just call yield. (Again, implementation)

A: Thread.sleep() will just pause the thread and not give away control.
Thread.yield() will pause the thread and allow other threads to run. If no threads need to, the original thread will resume immediately.


text:
Q: How does Spring-JPA EntityManager handle "broken" connections? I have an application that uses a Spring-EntityManager (JPA) and I wonder what happens if the database happens to be unavailable during the lifetime of my aforesaid application.
I expect in that situation it will throw an exception the first time to do anything on the database, right?
But, say I wait 10 minutes and try again then and the DB happens to be back. Will it recover? Can I arrange it so it does?
Thanks

A: Actually, neither Spring nor JPA have anything to do with it. Internally all persistence frameworks simply call DataSource.getConnection() and expect to receive (probably pooled) JDBC connection. Once they're done, they close() the connection effectively returning it to the pool.
Now when the DataSource is asked to give a connection but database is unaivalable it will throw an exception. That exception will propagate up and will be somehow handled by whatever framework you use.
Now to answer your question - typically DataSource implementation (like dbcp, c3p0, etc.) will discard connection known to be broken and replace it with a fresh one. It really depends on the provider, but you can safely assume that once the database is available again, the DataSource will gradually get rid of sick connections and replace them with healthy ones.
Also many DataSource implementors provide ways of testing the connection periodically and before it is returned to the client. This is important in pooled environemnts where the DataSource contains a pool of connections and when the database becomes unavailable it has no way to discover that. So some DataSources test connection (by calling SELECT 1 or similar) before giving it back to the client and do the same once in a while to get rid of broken connections, e.g. due to broken underlying TCP connection.
TL;DR
Yes, you will get an exception and yes the system will work normally once the database is back. BTW you can easily test this!


text:
Q: ChannelSftp.put method gets stuck when using input stream from ChannelSftp.get
My scenario is:
I'm using Jsch lib(v - 0.1.54), to work with SFTP
Everything works fines except when I try to use sftpChannel.put() method, it uploads the file but the process get stuck
Code:
public static void moveFiles() {
    //some code
     try {
           InputStream fis =  sftpChannel.get(currentDirectory+"/"+fileName);

           sftpChannel.put(fis, fileName,  ChannelSftp.RESUME);//"freezes here, no exception is thrown

           fis.close();
         } catch(Exception e){
            e.printStackTrace();
         }
    //some other code
}

I've checked if there's already any other issue like that one I'm facing but there's is no solution to it(apparently)
Same issue
Thanks in advance o/

A: I figure it out the solution after digging further the matter
I need one ChannelSftp to get the file and another one ChannelSftp to use put
  public static void moveFiles() {
      //some code
    ChannelSftp sftpChannel = getChannel();
    ChannelSftp sftpChannelDownload = getChannel();
     try {
        InputStream fis = sftpChannelDownload.get(currentDirectory+"/"+fileName);
        sftpChannel.put(fis, fileName);
    }  catch(Exception e){
        e.printStackTrace();
    }
    //more code
  }


text:
Q: The dispersion relation and the critical wavelength A semi-infinite layer of incompressible inviscid fluid with density ρ1 occupies the half-space $y < 0$ below a similar layer of fluid with density $\rho_2 < \rho_1$ occupying $y > 0$. The lower fluid flows at uniform speed U in the x-direction while the upper fluid flows at speed V in the x-direction. The surface tension on the interface between the two fluids is negligible.
The flow is disturbed by small-amplitude irrotational waves such that the free surface initially at $y = 0$ is displaced to $y = \eta(x, t)$. You may assume that the velocities in the lower and upper fluids take the forms
$$\mathbf u_1 =U \mathbf i+ \nabla \varphi_1 , \quad \mathbf u_2 =V\mathbf i+∇φ_2$$
Show that harmonic travelling waves, with  $ η(x, t) = A cos(kx − ωt)$ and k > 0, are possible provided ω and k satisfy the dispersion relation
$$\rho_1(\omega − U k)^2 + \rho_2(ω−Vk)^2 =(\rho_1 − \rho_2)gk$$
Deduce that, whenever U $\neq$ V , the free surface is unstable to waves whose wavelength is smaller than the critical value
$$λ_c=\frac{2πρ_1ρ_2(U-V)^2}{(\rho_1^2−\rho_2^2)g}$$
I got the dispersion relation but don't know how to get to the stable free surface part.I know w can be negative for some value of k. For these wave numbers, w is pure imaginary so the disturbance grows exponentially.Which means no stable. And $\lambda =\frac{2\pi c}{w}$But how to get the critical $\lambda_c$ ?
Thank you so much!

A: Given the dispersion relation, we can solve for the frequency and find:
$$\omega \,=\, \frac{(\rho_{1}U+\rho_{2}V)k \pm \sqrt{gk(\rho_{1}^{2}-\rho_{2}^{2}) - k^{2}(U-V)^{2}\rho_{1}\rho_{2}\;}}{\rho_{1}+\rho_{2}} $$
(I'll leave you to fill in the details!). As you note, the instability occurs when the frequency becomes imaginary; this occurs when the square root above goes negative or $k<k_{c}$ where this critical $k$ is found by solving:
$$\begin{align}
gk_{c}(\rho_{1}^{2}- \rho_{2}^{2}) - k_{c}^{2}(U-V)^{2}\rho_{1}\rho_{2} &\,=\, 0
\end{align}$$
yielding $k_{c}=0$ or
$$\begin{align}
 k_{c} &\,=\, \frac{g(\rho_{1}^{2}-\rho_{2}^{2})}{\rho_{1}\rho_{2}(U-V)^{2}}
\end{align}$$
(again, I will leave you to complete the algebra!). The relation $\lambda_{c}=\frac{2\pi}{k_{c}}$ then yields the relation you are after.


text:
Q: How can webpack devServer accept other paths except root / in the browser? I followed the webpack setting from https://createapp.dev/ then made my sources from create-react-app to webpack.
But I have a problem for hot-realoding. The browser can't accept any router paths except / when I revised pages except /.
When I run webpack devserver by 'yarn start', hot reloding is good for '/' for example: http://localhost:4000. but fail to other paths for example "/main", "/login" etc...
The error message is for example when I tried to refresh /main, then I got 'Cannot GET /main'.
I tried to find some of resources like adding 'inline : true' in webpack setting and also added hot too.
I also find other people's article but they only show / page hot reloading not like other page component hot reloading.
I also refered this site.
https://github.com/gaearon/react-hot-loader/issues/1150
// webpack.config.js
const webpack = require('webpack');
const path = require('path');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const config = {
    entry: [ 'react-hot-loader/patch', 'react-hot-loader/babel', './src/index.tsx' ],
    output: {
        publicPath: './dist',
        path: path.resolve(__dirname, 'dist'),
        filename: '[id].bundle.js',
        chunkFilename: '[id].js' // will auto assign a id to your separate chunks
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ],
                exclude: /\.module\.css$/
            },
            {
                test: /\.ts(x)?$/,
                use: [ 'awesome-typescript-loader' ],
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader',
                        options: {
                            importLoaders: 1,
                            modules: true
                        }
                    }
                ],
                include: /\.module\.css$/
            },
            {
                test: /\.svg$/,
                use: 'file-loader'
            },
            {
                test: /\.png$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            mimetype: 'image/png'
                        }
                    }
                ]
            }
        ]
    },
    resolve: {
        extensions: [ '*', '.js', '.jsx', '.tsx', '.ts', '.css', '.sa' ],
        alias: {
            'react-dom': '@hot-loader/react-dom'
        }
    },
    devServer: {
        port: 4000,
        contentBase: './dist',
        proxy: {
            '/myserver': {
                target: {
                    host: 'localhost',
                    protocol: 'http:',
                    port: 8080
                }
            }
        },
        hot: true
    },
    "devtool": "source-map",
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
        new LodashModuleReplacementPlugin(),
        new HtmlWebpackPlugin({
            template: 'index.html',
            inject: false,
            appMountId: 'app'
        })
    ],
    optimization: {
        runtimeChunk: 'single',
        splitChunks: {
            cacheGroups: {
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all'
                }
            }
        }
    }
};

module.exports = (env, argv) => {
    if (argv.hot) {
        // Cannot use 'contenthash' when hot reloading is enabled.
        config.output.filename = '[name].[hash].js';
    }

    return config;
};

//index.tsx
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactDOM from 'react-dom';
import * as React from 'react';
import "core-js/modules/es.promise";
import "core-js/modules/es.array.iterator";

if (module.hot) {
    ReactDOM.render(<App />, document.getElementById('app'));
    module.hot.accept();
}

//App.tsx
import { store, persistor } from './redux/store';
import Framework from './layouts/Framework';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import * as React from 'react';
import { hot } from 'react-hot-loader/root'

class App extends React.Component {
    render() {
        return (

                <Provider store={store}>
                    <PersistGate loading={null} persistor={persistor}>
                        <Framework />
                    </PersistGate>
                </Provider>

        );
    }
}
export default hot(App);

Overall
/ => hot-reloading success in the browser after component revised or refresh in the browser
/main, /firstComp, /secondComp etc... => hot-reloading fail in the browser after component revised or refresh in the browser. it shows can't get /{page address}
I want get any page hot-realoding from my webpack.
Thank you.

A: I have not see a webpack setup like that before, I chunk by id, I will post those parts here in case it will help you.
entry: "./src/App.js", // This is the component were I wrap routes in app
  output: {
    publicPath: './dist',
    path: path.resolve(__dirname, "dist"),
    filename: "[id].bundle.js",
    chunkFilename: "[id].js", // will auto assign a id to your separate chunks
  },

import React from 'react';
import Routes from './routes/routes'; // Figured I would show you that
const App = () => {
    return (
<Routes />
 );
}

export default App;

resolve: {
    extensions: ["*", ".js", ".jsx", ".css", ".sa"]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.ModuleConcatenationPlugin(),
    new CompressionPlugin({
      cache: true,
      algorithm: "gzip",
      compressionOptions: {
        level: 5,
        minRatio: 0.8
      }
    }),
    new BundleAnalyzerPlugin({
      options: {
        generateStatsFile: true
      }
    }),
    new HtmlWebpackPlugin({
      template: "./public/index.html" // The path to your html
    })
  ],
  devServer: {
    contentBase: "./dist", // Where my file bundles are served from served from
    hot: true            // Enable hot loading
  },
  "devtool": "source-map"
};

Then in my index.js enable hot;
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));
module.hot.accept();

I had trouble with getting this to work until I found I needed these imports, also at the top of index.js
import "core-js/modules/es.promise";
import "core-js/modules/es.array.iterator";

There are so many parts of webpack that I do not have any experience with,so hopefully this helps.


text:
Q: The probability to log on a computer from a remote terminal is 0.7. The probability to log on a computer from a remote terminal is $0.7$. Let $X$ denote the number of attempts that must be made to gain access to the computer.
Find:
(a) The distribution of $X$ and prove that is correctly defined
A:geometric distribution,f:N->(0;1]
(b) The expected value of attempts needed to gain access
A:f(k)=0.7*0.3^(k-1)
(c) The probability that at most three attempts, respectively at least two attempts must be made to gain access.
A:f(3)=0.7*0.3^2
A:f(2)=0.7*0.3
Can someone help me with this problem? I don't know what kind of distribution should I pick for $X$. Can someone tell me if my answer are rights ?
That's all the info I've got for the problem.

A: Since you ask for guidance and not the complete anawer: (a) $X$ is geometric.  (b) there's a simple formula for the mean of a geometric, (c) sum of the geometric over a subset of the range.
You see how $X$ is like flipping a coin over and over till you get a head?  But the coin is not a fair coin it's $0.7$ heads $0.3$ tails.  That's the basic formula for a geometric.


text:
Q: Do not see BizTalk projects in VS 2010 Ultimate I have a Visual Studio 2010 Ultimate installed on my local machine. I used it for c# development for quite some time.
Now I have a project for BizTalk development. When I click New Project I do not see the BizTalk project option.
What do I need to do to get BizTalk projects on my Visual Studio 2010 Ultimate?

A: You will need to download a version of BizTalk from Microsoft and install at least the developer tools and SDK.  But usually you will want to do a complete install unless you already have a BizTalk Server you can deploy to for development purposes.
See this thread What do you need to develop in BizTalk

A: Step1:
Launch BizTalk Setup>Modify>Unselect 'Developer tools SDK'>Complete the installation.
Step 2:
Launch BizTalk Setup>Modify>Select 'Developer tools SDK'>Complete the installation.
After you have performed Step1 and Step 2, or you may have not Installed Developer Tools SDK then perform only Step 2.
Start>>Visual Studio 2010 >> Biztalk >> Biztalk Empty Project>> If you now see it then you can assume that your Developer Tools have been successfully installed.
https://social.technet.microsoft.com/wiki/contents/articles/25177.biztalk-server-start-developing-a-simple-biztalk-application-for-biztalk-beginners.aspx


text:
Q: How to add progress bar until loop execution is finished? I am developing an android app where I need to show a ProgressBar until the loop execution is finished. After execution it will go to the nextActivity.
here is my java code
    public class Image_Recognition extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image__recognition);

        Button btnNextPage = (Button) findViewById(R.id.btnNextPage);

            btnNextPage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

                        Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                        SparseArray<TextBlock> items = textRecognizer.detect(frame);
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < items.size(); ++i) {
                            TextBlock item = items.valueAt(i);
                            stringBuilder.append(item.getValue());
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append('.');
                        txtResult.setText(stringBuilder.toString());

                        str = stringBuilder.toString();
                        Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
                        myintent.putExtra("translate", str);
                        startActivity(myintent);

                }
            });
        }
    //}
}

A: You have two problems here.
ProgressBar, which you can use ProgressDialog or a ProgressBar in your XML and show it, while hiding the rest of your IU.
Blocking the UI
You are running your loop directly from you click listener, which means that you will block your UI and even if you show some sort of progress, it will be blocked till your loop is over, you need to start a thread and run your loop in.
Here's a not very clean version of you click listener impl
final ProgressDialog dialog = new ProgressDialog(Image_Recognition.this);
        dialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

                Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                SparseArray<TextBlock> items = textRecognizer.detect(frame);
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < items.size(); ++i) {
                    TextBlock item = items.valueAt(i);
                    stringBuilder.append(item.getValue());
                    stringBuilder.append("\n");
                }
                stringBuilder.append('.');
                txtResult.setText(stringBuilder.toString());

                str = stringBuilder.toString();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
                        myintent.putExtra("translate", str);
                        startActivity(myintent);
                    }
                });
            }
        }).start();

A: You could use Async Task and run your loop in doInBackground()
class MyTask extends AsyncTask<Void, Void, Void> {
    ProgressDialog pd;
    public MyTask(ProgressDialog pd){
        this.pd=pd;
    }
    @Override
    protected void onPreExecute () {
        super.onPreExecute();
        pd.setMessage("Uploading . . .");
        pd.show();
        pd.setCancelable(false);
    }

    @Override
    protected Void doInBackground (Void...voids){
        for(int i=0;i<10000000;i++){
            System.out.print(i);
        }
        return null;//download file
    }

    @Override
    protected void onPostExecute (Void aVoid){
        super.onPostExecute(aVoid);
        pd.dismiss();
    }
}

and in activity call new MyTask(pd).execute();

A: You can try with this.
final ProgressDialog dialog = new ProgressDialog(Image_Recognition.this);
btnNextPage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    dialog.show(Image_Recognition.this, "", "Please wait...", true);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

                            if (!textRecognizer.isOperational())
                                Log.e("ERROR", "Detector dependencies are not yet available");
                            else {

                                Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                                SparseArray<TextBlock> items = textRecognizer.detect(frame);
                                StringBuilder stringBuilder = new StringBuilder();
                                for (int i = 0; i < items.size(); ++i) {
                                    TextBlock item = items.valueAt(i);
                                    stringBuilder.append(item.getValue());
                                    stringBuilder.append("\n");
                                }
                                stringBuilder.append('.');
                                txtResult.setText(stringBuilder.toString());

                                str = stringBuilder.toString();
                            }

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.dismiss();
                                    dialog.setCancelable(true);
                                    Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
                                    myintent.putExtra("translate", str);
                                    startActivity(myintent);
                                }
                            });
                        }
                    },5000);


text:
Q: how to send an email in asp.net mvc4 i want to send an email using a asp.net mvc 4 application   i am using this  method
     public void send_mail(ProcRec.Models.AccuseReception _objModelMail)
    {

        MailMessage mail = new MailMessage();
        mail.To.Add(_objModelMail.To);
        mail.From = new MailAddress(_objModelMail.From);
        mail.Subject = _objModelMail.Subject;
        string Body = _objModelMail.Body;
        mail.Body = Body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential
        ("username", "password");// Enter seders User name and password
        smtp.EnableSsl = true;
        smtp.Send(mail);

    }

My  model  :
            public class AccuseReception
{

    public string From { get; set; }
    public string To { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }

}

controller   :
        if (ModelState.IsValid)
        {

           AccuseReception confermation_mail = new AccuseReception {

            From="xxxxxxxxxxx@gmail.com",
            To ="ssssssss@gmail.com",
            Subject ="mail_de confermation",
            Body = "votre demande est enregistrer ",

            };

        send_mail(my_mail);
         }

i  get  no error  but the mail is not sending   and   the ModelState is not valid

A: ModelState belongs to a model that is passed to corresponding view/controller.
I see that in your controller you create a new AccuseReception so i assume that you are not getting AccuseReception as a model in this controller action.
This is the reason your ModelState.IsValid returns false and no mails are sent.
Try something like:
 public void SendMail(ProcRec.Models.AccuseReception _objModelMail)
 {
       if(ModelState.IsValid)
       {

           MailMessage mail = new MailMessage();
           mail.To.Add(_objModelMail.To);
           mail.From = new MailAddress(_objModelMail.From);
           mail.Subject = _objModelMail.Subject;
           string Body = _objModelMail.Body;
           mail.Body = Body;
           mail.IsBodyHtml = true;
           SmtpClient smtp = new SmtpClient();
           smtp.Host = "smtp.gmail.com";
           smtp.Port = 587;
           smtp.UseDefaultCredentials = false;
           smtp.Credentials = new System.Net.NetworkCredential
           ("username", "password");// Enter seders User name and password
           smtp.EnableSsl = true;
           smtp.Send(mail);
        }
   }

A: Here's a vb.net example that should work for you. I can't see your model in the example. But that should be enough:
Dim smtpClient As New SmtpClient(_ServerHost, _ServerPort)
smtpClient.Credentials = New Net.NetworkCredential(_EmailAddress, _EmailPass, String.Empty)
smtpClient.EnableSsl = True
smtpClient.Timeout = 60000

Dim mailmsg as New MailMessage
mailmsg.Subject = i_Subject
mailmsg.From = New MailAddress(emailAddress, displayName)
mailmsg.To.Clear()
mailmsg.IsBodyHtml = True
mailmsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure

' Add email addresses
mailmsg.To.Add("someemail@gmail.com")

mailmsg.Body = SomeBodyHTML

If Not String.IsNullOrEmpty(mailmsg.Body.Trim) Then
    ' Send message
    smtpClient.Send(mailmsg)
End If

BTW if you want to easily send more complex html as emails, you can use Postal. In Postal you build views that are sent as emails:
aboutcode.net/postal


text:
Q: Google Earth Engine returning white images When I run the following code, a blank image is outputted.
coordinates = input()
geoCoordinates = json.loads(coordinates)
i_date = '1972-07-25'
f_date ='2022-12-31'
aoi = ee.Geometry.Polygon(geoCoordinates)
images = ee.ImageCollection("LANDSAT/LC09/C02/T2").filterBounds(aoi).filterDate(i_date, f_date)
image = ee.Image(images.first()).clipToBoundsAndScale(aoi)
url = image.select("B4").getThumbURL()
disp.Image(url = url, width = 800)

Does anyone know why and how I can fix this?

A: First, you need to use var in order to introduce new variable into to GEE.
Second, you used getThumbURL without providing visualization parameters. These include dimension, region, and format of your image. Also you could use extra visualization parameters defined in ee.data.getMapId.
Third, I suggest using collection 2, Tier 1, level 2 or level 1 since they are Landsat data with the highest quality.
Also, you need to use print in order to see the link in your GEE console.
Your syntax is not reproducible. Here I provide the one that you can check on your machine.
Last point, there is a function prepSrL8 I used for choosing Landsat scenes based on their quality (QA bands).
var i_date = '1972-07-25'
var f_date ='2022-12-31'

var aoi = ee.Geometry.MultiPoint([
[46.72759630878907,38.171211790897694],
[48.38103869160157,38.171211790897694],
[48.38103869160157,39.25559070083476],
[46.72759630878907,39.25559070083476],
[46.72759630878907,38.171211790897694]
  ]).bounds()
Map.centerObject(aoi, 8)
Map.addLayer(aoi, {}, 'Area of Interest')

var images = ee.ImageCollection("LANDSAT/LC09/C02/T1_L2")
            .map(prepSrL8)
            .filterBounds(aoi)
            .filterDate(i_date, f_date)

var image = ee.Image(images.first()).clip(aoi); print (image)
Map.addLayer(image.select('SR_B4'),{min: 0, max: 0.25})

var gifParams = {
  'region': aoi.buffer(2000).bounds(),
  'dimensions': 1024,
  'bands': "SR_B4",
  'min': 0,
  'max': 0.25,
  'format': 'jpg'
};

var url = image.getThumbURL(gifParams)
print(url)

function prepSrL8(image) {
  // Develop masks for unwanted pixels (fill, cloud, cloud shadow).
  var qaMask = image.select('QA_PIXEL').bitwiseAnd(parseInt('11111', 2)).eq(0);
  var saturationMask = image.select('QA_RADSAT').eq(0);

  var optical = image.select("SR_B.").multiply(0.0000275).add(-0.2)
  var thermal = image.select("ST_B.*").multiply(0.00341802).add(149)
      // Approximate 0 to 1 range.
      .subtract(270)//.divide(50)

  // Replace original bands with scaled bands and apply masks.
  return image.addBands(ee.Image.cat(optical, thermal), null, true)
    .updateMask(qaMask).updateMask(saturationMask);
}


text:
Q: How to scrape train route data from https://rbs.indianrail.gov.in/ShortPath/ShortPath.jsp i am trying get list of intermediate railway stations information from https://rbs.indianrail.gov.in/ShortPath/ShortPath.jsp, by providing source and destination stations it displays list of intermediate stations within a table. but its hiding some intermediate stations under several buttons to limit the size of the table,i think. on clicking the buttons, it pushes hidden data on to the table.  using jsoup i could get initial data in the table. but dont know how to get the hidden data. on button click, one javascript function requesting data using POST method from https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet by passing "route=inter,index=1,distance=goods,PageName=ShortPath" as parameters and the response is in json. as the parameters are not relevant to the displayed table, i can not make direct request to the https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet.
        private void shortestPath(String source, String destination) {

        Document doc;
        try {
            doc = Jsoup.connect(url)
                    .data("srcCode", source.toUpperCase())
                    .data("destCode", destination.toUpperCase())
                    .data("guageType", "S")
                    .data("transhipmentFlag", "false")
                    .data("distance", "goods")
                    .post();
            Element table = doc.select("tbody").get(0);
            Elements rows = table.select("tr");
            stationCodeList = new String[rows.size() - 3];
            jsonPath = new JSONObject();
            for (int row = 3; row < rows.size(); row++) {
                JSONObject jsonObject = new JSONObject();
                Elements cols = rows.get(row).select("td");
                String code = cols.get(1).text();
                String name = cols.get(2).text();
                String cum_dist = cols.get(3).text();
                String inter_dist = cols.get(4).text();
                String gauge = cols.get(5).text();
                String carry_cap = cols.get(6).text();

                jsonObject.put("Code", code);
                jsonObject.put("Name", name);
                jsonObject.put("Cumulative Distance", cum_dist);
                jsonObject.put("inter Distance", inter_dist);
                jsonObject.put("Gauge Type", gauge);
                jsonObject.put("Carrying Capacity", carry_cap);
                jsonPath.put(code, jsonObject);
                stationCodeList[row - 3] = code;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.destination =new Station(stationCodeList[stationCodeList.length-1]);
    }

thank you in advance

A: If you take a look at this answer, you'll see how to get the exact same request the browser has made.
The minimal and valid POST request to the StationXmlServlet, using your example, would look something like this with curl:
curl --request POST 'https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -H 'Cookie: JSESSIONID1=0000ob7e89cT3vUAYkBxF6oyW4w:APP2SERV1' \
  --data-raw 'route=inter&index=1&distance=goods&PageName=ShortPath'

As the parameters are not relevant to the displayed table, i can not make direct request to the https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet.

I don't think that's true. The index in the body of the request is the zero-based index of rows in the master table.

Solution
It turns out that you simply have to follow the exact same order as you do when you use the page in a web browser. In other words, you have to first load the master table so that the site knows which table you are viewing when you want to query for details. A session cookie keeps track of this state.
First, you open the landing page and get a Cookie:
HttpRequest cookieRequest = HttpRequest.newBuilder()
    .uri(URI.create("https://rbs.indianrail.gov.in/ShortPath/ShortPath.jsp"))
    .GET()
    .build();
HttpResponse<String> cookieResponse =
    client.send(cookieRequest, BodyHandlers.ofString());
String cookie = cookieResponse.headers().firstValue("Set-Cookie").get();

Next, you load the master table, given the specified form parameters:
HttpRequest masterRequest = HttpRequest.newBuilder()
    .uri(URI.create("https://rbs.indianrail.gov.in/ShortPath/ShortPathServlet"))
    .header("Content-Type", "application/x-www-form-urlencoded")
    .header("Cookie", cookie)
    .POST(BodyPublishers.ofString("srcCode=RGDA&destCode=JSWT&findPath0.x=42&findPath0.y=13&gaugeType=S&distance=goods&PageName=ShortPath"))
    .build();
HttpResponse<String> masterResponse =
    client.send(masterRequest, BodyHandlers.ofString());
String masterTableHTML = masterResponse.body();
// Document masterTablePage = Jsoup.parse(masterTableHTML);
// ...

Finally, you can query the details for each row of the master table. In the example bellow, we query the details of the first row.
HttpRequest detailsRequest = HttpRequest.newBuilder()
    .uri(URI.create("https://rbs.indianrail.gov.in/ShortPath/StationXmlServlet"))
    .header("Content-Type", "application/x-www-form-urlencoded")
    .header("Cookie", cookie)
    .POST(BodyPublishers.ofString("route=inter&index=0&distance=goods&PageName=ShortPath"))
    .build();
HttpResponse<String> detailsResponse =
    client.send(detailsRequest, BodyHandlers.ofString());
String jsonResponse = detailsResponse.body();
System.out.println(jsonResponse);


text:
Q: Windows command-line utility to convert Access .mdb database to MySQL or SQL Server? Is there any program that can convert an Access .mdb database to a MySQL or SQL Server database by command line so I can use it and enter the required command line from my application?

A: Please refer following links to convert mdb file to mysql file format
How to import an Access MDB format database to MySQL?
How can I convert an MDB (Access) file to MySQL (or plain SQL file)?
http://www.bullzip.com/products/a2m/info.php

A: SQL Server Migration Assistant has command line options. See the following link.
http://blogs.msdn.com/b/ssma/archive/2010/09/09/performing-database-migration-assessment-using-ssma-console-application.aspx?Redirected=true


text:
Q: How to determine new thrust input to move current coordinate to specified coordinate position So say I have a drone in X,Y space at a known position (X1,Y1) with an orientation of 45 degrees to the right with respect to origin in the coordinate system (see example below).

The red arrow depicts the front face of the drone and the orange point represents where it is in space (X1,Y1).
Knowing the drone has thrust input for forward and backward motion (which range from +1 (forward) to -1 (backward); and leftward, and rightwards motion (which range from +1 (rightward) to -1 (leftward). With respect to the drones front face (see example below shown in purple).

How would I go about determining the thrust input to reach a new point in the coordinate system (X2,Y2) taking into account the orientation of the drone. Forgive my crude mspaint drawings. Appreciate any help!

A: The way your question is posed, I assume you do not want to turn the drone.
Let's give some names to the points: A = (X1, Y1), B = (X2, Y2).
The direction you want to move is D = normalize(B - A).
The front of the drone is facing U = (cos(a), sin(a)) where a is the angle.
The right side of the drone is facing V = (sin(a), -cos(a)).
If you turn the forward/backward thruster on proportional to dot(D, U) and the left/right thruster on proportional to dot(D, V), you will move in the direction you want. (This is called a change of basis.)
You can scale (dot(D, U), dot(D, V)) uniformly to increase or decrease the speed.


text:
Q: Mac OSX System menu name w/Java? I have a slight problem. Having recently migrated on Mac, I've been pulling my hair and searching the web about this but have not found what I was exactly searching for. I want to set the application name in the system menu, which doesn't work at the moment (my main class name is displayed instead of my app name). What property should I modify?
I have successfully placed my menu in the system menu bar using the correct apple.laf property, but I haven't found what I needed for the name.
My search led me to Info.plist documents, on which I have no knowledge whatsoever. I tried to make a simple one that would only change the app's display name, but for some reason it hasn't worked. Help?

A: According to sun's documentation you would pass the name into the virtual machine as a command line parameter to the java command with -Xdock:name="{AppName}" replacing {AppName} with what you want to appear as the title in the Menu bar.
Edit:
I do not believe that you can set this in the actual Java code itself, but as Chuck said Apple does have a program Jar Bundler which is designed to create the jar with the Info.plist that you need. According to the user guide for it, you need to set the Bundle Name property on the properties pane to get what you want.

A: Try using the included Jar Bundler, which is there to handle all this stuff for you. And if you want to see how any particular feature works, you can inspect Jar Bundler's output.

A: There is two ways:

*

*when you call: java -Xdock:name=myAppName

*In run time before any GUI interaccion:
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "myAppName!");

A: Settings any of the proposed Java (with -D in the launch shell script) properties didn't work for me, because they're only for AWT & Swing GUIs. Even the Mac specific -Xdock:* options did't work.
What did work is using this Project https://github.com/codecentric/NSMenuFX
In my JavaFX Controller for the menu I added the following snippet:
  public void initialize() {
    if ("Mac OS X".equals(System.getProperty("os.name"))) {
      final MenuToolkit tk = MenuToolkit.toolkit();
      final Menu defaultMacApplicationMenu = tk.createDefaultApplicationMenu("My App");
      tk.setApplicationMenu(defaultMacApplicationMenu);
    }
  }

Now the bold name of the Menu itself cannot be set using this library, but you can control that setting CFBundleDisplayName in the Info.plist of your application bundle.


text:
Q: Programming language for video As a big-fan of latex/PDF, I am looking for counterpart in video world. More specifically, latex can used to produce document, slides, and vector graphics in PDF format, which is essentially lossless and can be converted into other formats. Is there any programming language which can produce a "vector graphical" video in certain standard file format, which can convert to other video formats.
For video, it is better to be able to add sound track(.mp3).


text:
Q: Count DIVs with specific class where class name is a variable I have some problem with this code...
$("select#kronologia option").each(function() {
    var classname=$(this).val();
    alert($("article."+classname).length);
});

Error: Syntax error, unrecognized expression: article.
I want to count divs with specific class where the class name comes from a select field. I got syntax error. See above...
If i change this line
var classname=$(this).val();

to this
var classname="2013";

the script is OK.
Any help would be great...

A: Try changing var classname=$(this).val(); to var classname=str($(this).val());

A: what is article there? Is it a class prefix or id prefix
$("select#kronologia option").each(function() {
    var classname=$(this).val();
    alert($(".article"+classname).length);
});

or
$("select#kronologia option").each(function() {
    var classname=$(this).val();
    alert($("#article"+classname).length);
});

A: When you search for Class using JQuery there should be prefix "." a basic rule.
You have done everything fine just  append prefix for searching with class name as below.
alert($(".article"+classname).length);

https://codepen.io/JayPatel758/pen/wdpavo

A: Here's the updated JSFiddle.
The problem is that your first value is empty, therefore jquery will try to find elements matching article. (empty option value), that is indeed an incorrect expression. As you can see in the fiddle, when the value is empty it's skipped and your script will work. Ofcourse you can alter the behaviour of an empty value to your own needs.
$('select#kronologia').on('change', function(e) {
    $(this).find('option').each(function() {
        var classname = $(this).val();

        if (classname === '') {
            return true;
        }

        alert($('article.'+classname).length);
    });
});


text:
Q: Using IoC in an application that use a library that doesn't use IoC I am currently using a library (SuperWebSocket) which is a websocket server library that use a bootstrap which know which instances to load from a configuration file. I have implemented a bootstrap class for this (however the instances arent loaded using IoC). Also the commands from this server are loaded from assemblies reflection. I wanted to use this server in conjonction with my DAL and service layer which use IoC. My main problem is that i can't find a way to put this Console Application (Server) and cooperation with the lib in an IoC scenario without having to end up using the ServiceLocator.
Normally the kernel (Ninject) should be located at the composition root (Look like to be the best practice from many around..) which is rather not possible to do in this case or at least i didn't found how so that why i am here. Also the commands are loaded from assemblies reflection. I could implement a CommandLoader however this is still a problem cause they all inherit from the same interface (Multibinding maybe?). I could make custom interface for each of them but i still can't find a way to load them automatically. Even if i found a way to load them, i still have to be able to get service from attributes which is not easy to do.
Any suggestions ?

A: If I understand your question correctly then the library is the entry point for all work done. In this situation it depends on the framework what to do. Here are some things you can do the first things are the preferred ones:

*

*Inspect the library and find some way to hook into the framework to intercept the creation of your objects.

*Call kernel.Inject(this) after an object is created by the library. Have a look at the Ninject.Web extension. There we added some base classes e.g. NinjectWebPage for WebPage. This new base class calls kernel.Inject after creation. New web pages can now be derived from that base class and use property injection to get dependencies.

*Use the ServiceLocator pattern in the objects created by the libray. But just at this level. Anything deeper should use dependency injection.


text:
Q: Is there any efficient way (library or function or algorithm) to delete or append specific row and column component in Compressed Sparse Row format? Is there any efficient way (library or function or algorithm) to delete or append specific row and column component in Compressed Sparse Row format??
I'm using intel compiler however there are no any function to do that in Math Kernel Library.
So I need any information to delete or to append specific row and column data in CSR format.


text:
Q: Run a script at specified time in linux I have created scripts and now I want them to run automatically at specified time, how can I do that?
I am using Ubuntu and JAVA to write my scripts.

A: You can use crontab to do this in a specific time continuously.
To edit a crontab entries, Login as root user (su – root) and do crontab -e as shown below. By default this will edit the current logged-in users crontab.
root@dev-db# crontab -e

Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as
  shown below. This will execute the Full backup shell script
  (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.
30 08 10 06 * /home/ramesh/full-backup

More example here, and the crontab utils can be found here


text:
Q: Printing Bitwise NOT operator with hexadecimal format specifier If i'm using m instead of ~m then the code gives me the expected hexadecimal value of 32 but here it's giving ffffffdf as output.
EDIT
I know how bitwise ~ NOT operator works. But i'm not understanding this.Could somebody explain this...??
#include<stdio.h>

int main()
{
    unsigned int m = 32;
    printf("%x\n", ~m); //ffffffdf is printed as output

    return 0;
}

A: Every hexadecimal digit is four bits. Since you got 8 hexadecimal digits your integers seems to be 8*4=32 bit.
The NOT of 32 = 000000000000000000000000000010000 would be something like 11111111111111111111111111101111 which would be the hexadecimal digits above.

A: In C, ~ is the bitwise-not operator. You said you understand how this operator works, but your question indicates that you do not. So let's go through this example:
First, you declare m to be an unsigned int, which happens to be 32 bits wide on your platform. You assign it the decimal value 32. The variable m is 0x00000020.
Then, you print it out. When you print it out normally, the expected output appears. But when you print it out with the ~ operator, you get something completely different.
The ~ (bitwise-not) operator does exactly what it says on the tin: It negates (flips) every bit, so 1s become 0s and 0s become 1s. Let's see what that would do to your number:
 m = 0b00000000000000000000000000100000 = 0x00000020
~m = 0b11111111111111111111111111011111 = 0xffffffdf

As you can see, the result exactly matches what is being output, which is good -- it means both your compiler and CPU are working as expected!


text:
Q: Index of array looks like function name I learning about laravel and php and recently I have encountered some problem which I try  to describe:
I'm trying to echo an average age of male. I'm using this function which I found on forum related to laravel:
$resultMale = DB::select($maleSQL, array(1));
My problem is that it returns arrays which indexes are taken from this query
$maleSQL = "SELECT books.name, books.book_date, AVG(reviews.age) FROM books, reviews where name='{$this->name}' and sex='m' and {$this->condition};";
and so if I want to access to data which is indexed as "name" I use:
echo "{$resultMale[0]->name}";
But my problem starts when i try to access data under AVG(reviews.age)
 echo "{$resultMale[0]->AVG(reviews.age)}";

It is detected as a function inside this array not as an index.
error in laravel
I've tried using foreach loop as well as:
 $bypassFunctionAVG="avg(reviews.age)";
 echo "{$resultMale[0]->{$bypassFunctionAVG}}";

I've tried also renaming this index without success.
So there goes my question: how do I echo data of this array  under this index?

A: This might work...
$avg = $resultMale[0]->{"AVG(reviews.age)"}
echo $avg;

Otherwise, try using an alias (notice, "AS avg")
$maleSQL = "SELECT books.name, books.book_date, AVG(reviews.age) AS avg FROM books, reviews where name='{$this->name}' and sex='m' and {$this->condition};";

echo $resultMale[0]->avg;

Also double quotes is not necessary to echo variables as you have done it above. They are useful in some cases but not necessary. echo $var, echo "$var", echo "{$var}" will all do the same thing.
These things will have the same result...
$value = 25;
echo "The value is $value.";
echo "The value is {$value}.";
echo "The value is " . $value . ".";
echo 'The value is ' . $value . '.';

These will not have the same result as above...
// use {} around non-trivial variable expressions
echo "The value is $object->value.";

// single quotes don't do anything to variables
echo 'The value is $value.';


text:
Q: Reset counter variable on condition I have this simple "pagination" counter which is fetching the next page from an API. It works fine but the problem is that whenever I change category (movies or series) the counter obviously doesn't reset so instead of fetching the first page of the new category it continues from the number it left off.
I tried numerous conditional combinations but nothing really worked so far. I'm sure it's not that hard to solve I just can't think of the right logic to use.
let page = 1;
document.getElementById('load-more').addEventListener('click', () => {
    page++;

    const movies = document.getElementById('movies');
    const series = document.getElementById('series');

    if(movies.classList.contains('active-link')) {

        getMovies(page);

    } else if (series.classList.contains('active-link')) {

        getSeries(page);

    }
})

Reseting the let counter inside the if..else doesn't really work because every time I click the load more button it resets it back to page 1.

A: Use separate variables for the current movies page and the current series page. Also note that you can simplify your logic by using a single querySelector instead of selections followed by classList.contains:
let moviesPage = 1;
let seriesPage = 1;
document.getElementById('load-more').addEventListener('click', () => {
  if (document.querySelector('#movies.active-link')) {
    moviesPage++;
    getMovies(moviesPage);
  } else if (document.querySelector('#series.active-link')) {
    seriesPage++;
    getSeries(seriesPage);
  }
});

A: Set another event listener for the click on your #movies and  #series link,
and set the page variable to 1 at this place.
That would be the usual behavior when switching lists, one usually see a reset of paging.