text:
Q: How to Implement Google Search in Android SearchView What would be the proper way to Implement a Google Search with SearchView. For example, I press the Search button, and enter a query, and then after I hit enter button, it would do a google search in which I can get JSON data. All the examples I've seen are with lists or something similar. I'm trying figure out how to implement a Web search into SearchView

A: try using Google Custom Search api

A: I know this is old, but you should not put your SearchView searchView as a global variable, as that can lead to memory leaks. Instead, keep it as a local variable inside of onCreateOptionsMenu.

A: Figured it out! It was probably something to do with my Android Manifest or something:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.alexoladele.testingshit">

    <!-- Permissions's -->
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".SearchActivity" />

        <!-- Main Activity -->
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- SearchActivity -->
        <activity
            android:name=".SearchActivity"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>
    </application>

</manifest>

SearchActivity.java:
package com.alexoladele.testingshit;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.google.api.services.customsearch.Customsearch;

public class SearchActivity extends ListActivity {
    private static final String TAG = "SearchActivity";
    private String qry;
    private Customsearch customsearch;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        Log.i(TAG, "onCreate: ContentView was set to activity_search");

        Intent intent = getIntent();
        Log.i(TAG, "onCreate: Got Intent");

        Log.i(TAG, "onCreate: Handling Intent!");
        handleIntent(intent);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent(intent);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // Call detail activity for clicked entry
    }

    private void handleIntent(Intent intent) {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            qry = intent.getStringExtra(SearchManager.QUERY);
            Log.i(TAG, "handleIntent: QUERY: " + qry + "\n Starting the doSearch Method!");
            doSearch(qry);
        } else {
            Log.i(TAG, "handleIntent: Intent WAS NOT search");
        }
    }

    private void doSearch(String query) {
        Log.i(TAG, "doSearch: In doSearch Method!");
    }
}

MainActivity.java:
package com.alexoladele.testingshit;

import android.Manifest;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import layout.WelcomeScreenFragment;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    SearchView searchView;

    final static String[] NEEDED_PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_NETWORK_STATE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);

        if (ContextCompat.checkSelfPermission(getApplicationContext(), NEEDED_PERMISSIONS[0])
                != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(getApplicationContext(), NEEDED_PERMISSIONS[1])
                        != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(getApplicationContext(), NEEDED_PERMISSIONS[2])
                        != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, 808);
            Log.i(TAG, "onCreate: Requesting Permissions");

        }

//        Makes sure that the root_layout view is not null before doing anything
        if (findViewById(R.id.root_layout) != null) {

//            Makes sure that there's no saved instance before proceeding
            if (savedInstanceState == null) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction manager = fm.beginTransaction();
                manager
                        .add(R.id.root_layout, WelcomeScreenFragment.newInstance(), "welcomeScreen")
                        .commit();
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (808) {
            case 808:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(getApplicationContext(), "Permissions GRANTED", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Permissions NOT GRANTED", Toast.LENGTH_SHORT).show();

                }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);

//        VARIBLES TO USE
        MenuItem searchItem = menu.findItem(R.id.search);
        searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

//      Set Up the search Function
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        ComponentName componentName = new ComponentName(getApplicationContext(), SearchActivity.class);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName));
        searchView.setIconifiedByDefault(false);
        return true;
    }
}


text:
Q: How to prove infinite product converging to sin and cos? How to prove following statements in the simplest way:
$$
\sin(x)=x\prod\limits_{n = 1}^{\infty}\Big(1-\frac{x^2}{\pi^2n^2}\Big),\quad
\cos(x)=\prod\limits_{n = 1}^{\infty}\Big(1-\frac{4x^2}{\pi^2(2n-1)^2}\Big).
$$
We are learning infinite products, but the teacher just gave it to us without proof. I`ve read wikipedia and that material is too hard to understand(i mean Weierstrass factorization theorem, as proof follows from it). Is there any simpler way?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python re.match returns none. How to modify the search string? Below are my lines:
num1    -num2 num3: var.shift varstate=shift, var3=num, var4=False/True,  Shift   0xabc5d

num1    -num2 num3: var.shift varstate=shift, var3=num, var4=False/True,  Shift 0xabc08

num1    -num2 num3: var.shift varstate=shift, var3=num, var4=False/True,  Shift [38b]0xabc34

I am trying to get the hexvalue from the lines. I need the hexvalue in only one of the line which is in the form of [38b]0xabc1234567890000000000000000000000000. I dont need all the hex values.
All my hex values int he line start with 0x so I have given that in re.match
#!/usr/bin/env python
import sys
import re
import binascii
import string
value_file = open("test2.txt","r")
file2 = open("out.txt", "w")

for line in value_file:
    line_string = str(line)
    line_nospace = line.replace(" ", "")
    lines_cont = line_nospace.rstrip("\n")
    reg_match = re.match(r'\[([38b]]*)\](0-9a-zA-Z)', lines_cont)
    print reg_match

A: Your regular expression (.*) 0x(\.*) escapes the period in the second group, which means that it is matching zero or more periods rather than zero or more arbitrary characters.
If you want to match everything after the 0x, remove the back slash.


text:
Q: How to configure 2-level of hibernate entity cache via annotations properly I want to configure 2nd level hibernate cache at Spring Boot microservice.
And I don't want to use xml at all.
Next is my example.
UserEntity.java
@Entity
@Table(name = "users")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "users")
public class UserEntity {

    @Id
    private long id;

    @Column
    private String name;

    public UserEntity(long id, String name) {
        this.id = id;
        this.name = name;
    }

   // ... geters&setters
}

CacheConfig.java
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public org.springframework.cache.CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManager());
    }

    private net.sf.ehcache.CacheManager ehCacheManager() {

        CacheConfiguration usersCacheConfiguration = new CacheConfiguration();
        usersCacheConfiguration.setName("users");
        usersCacheConfiguration.eternal(false);
        usersCacheConfiguration.setMaxEntriesInCache(1000);
        usersCacheConfiguration.setMaxEntriesLocalDisk(0);
        usersCacheConfiguration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);

        net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
        config.addCache(usersCacheConfiguration);

        return net.sf.ehcache.CacheManager.create(config);
    }
}

App.java
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        new SpringApplicationBuilder(App.class)
                .sources(CacheConfig.class)
                .run(args);
    }

}

application.properties
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/test
    username: postgres
    password: postgres
    type: com.zaxxer.hikari.HikariDataSource
    driverClassName: org.postgresql.Driver
  jpa.hibernate.ddl-auto: update
  jpa.open-in-view: false
  jpa.properties.javax.persistence.sharedCache.mode: ALL
  jpa.properties.hibernate:
    dialect: org.hibernate.dialect.PostgreSQL9Dialect
    jdbc.batch_size: 100
    temp.use_jdbc_metadata_defaults: false
    order_inserts: true
    cache:
      region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
      #region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
      #region_prefix: ""
      use_second_level_cache: true
      cache.use_query_cache: true
      provider_class: org.hibernate.cache.EhCacheProvider

build.gradle
group 'com.hibernate.cache'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.0.RELEASE'
    compile group: 'org.springframework', name: 'spring-context-support', version: '5.0.4.RELEASE'
    compile group: 'org.hibernate', name: 'hibernate-ehcache', version: '5.2.14.Final'
    compile group: 'org.postgresql', name: 'postgresql', version: '42.1.4'
}

When I run the program I see a couple of warnings indicating that entity cache configuration is not applied:
2018-03-04 23:29:48.723  WARN 8516 --- [           main] n.s.ehcache.config.ConfigurationFactory  : No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/home/vitaly/.gradle/caches/modules-2/files-2.1/net.sf.ehcache/ehcache/2.10.3/cf74f9a4a049f181833b147a1d9aa62159c9d01d/ehcache-2.10.3.jar!/ehcache-failsafe.xml
2018-03-04 23:29:48.834  WARN 8516 --- [           main] o.h.c.e.AbstractEhcacheRegionFactory     : HHH020003: Could not find a specific ehcache configuration for cache named [users]; using defaults.

Does anybody know what is wrong here?

A: The first warning:
2018-03-04 23:29:48.723  WARN 8516 --- [           main] n.s.ehcache.config.ConfigurationFactory  : No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/home/vitaly/.gradle/caches/modules-2/files-2.1/net.sf.ehcache/ehcache/2.10.3/cf74f9a4a049f181833b147a1d9aa62159c9d01d/ehcache-2.10.3.jar!/ehcache-failsafe.xml

means that no ehcache.xml configuration was found so a default, ehcache-failsafe.xml, is used.
The second warning:
2018-03-04 23:29:48.834  WARN 8516 --- [           main] o.h.c.e.AbstractEhcacheRegionFactory     : HHH020003: Could not find a specific ehcache configuration for cache named [users]; using defaults.

means that there was no configuration found for the "users" region in the cache. It is, of course, not defined in ehcache-failsafe.xml and it doesn't look like the settings in CacheConfig are being picked up - at least not by the CacheManager used by Hibernate.
It should be possible to solve both by adding an ehcache.xml to the classpath (in src/main/resources), e.g.:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
         updateCheck="true"
         monitoring="autodetect"
         dynamicConfig="true">

    <cache name="users"
           maxEntriesLocalHeap="500"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           diskExpiryThreadIntervalSeconds="1"
           copyOnRead="true"
           copyOnWrite="true">
        <copyStrategy class="net.sf.ehcache.store.compound.ReadWriteSerializationCopyStrategy" />
    </cache>

</ehcache>

(see this ehcache.xml sample for more options)
And adding the following to application.yml:
spring:
  cache:
    ehcache:
      config: classpath:ehcache.xml

A: A year late but the answer to your question might require you to implement your own RegionFactory class (by extending SingletonEhCacheRegionFactory) And then set your newly created class as the factory that hibernate should use: spring.jpa.properties.hibernate.cache.region.factory_class=com.my.class
https://stackoverflow.com/a/28594371/708854


text:
Q: Tkinter: how to colorize the outline of a canvas rectangle? I draw a rectangle on a Canvas:
 canvas = Canvas(parent,  cursor="cross")
 rect = canvas.create_rectangle(20,20, 1, 1, fill="")

I only want to draw the border, leaving the interior transparent (that is why I set fill="" as mentioned here).
My problem:
I want the rectangle to have a red border. How can I do that?

A: From the page you linked:

outline=
Outline color. Default is "black".

A: By default, the interior of a rectangle is empty, and you can also get this
behavior with fill='' rather than just leaving it out.
If you want the rectangle outlined, just add a keyword argument named outline to the create_rectangle() call:
rect = canvas.create_rectangle(20,20, 1, 1, outline='red')

You can also control the width of the border by also adding a width=xxx keyword argument to the call. The default width is 1 pixel.


text:
Q: String gets mysteriously cut off In my application I use WpfLocalization to provide translations while the application is running. The library will basically maintain a list of properties and their assigned localization keywords and use DependencyObject.SetValue() to update their values when the active language is changed.
The scenario in which I noticed my problem is this: I have a simple TextBlock and have assigned a localization keyword for its Text property. Now when my application starts, it will write the initial value into it and it will display just fine on screen. Now I switch the language and the new value is set as the Text property but only half the text will actually display on screen. Switching the languages back and forth does not have any effect. The first language is always displayed fine, the second is cut off (in the middle of words, but always full characters).
The relative length of both languages to each other does not seem to have anything to do with it. In my test case the working language string is 498 bytes and the one that gets cut off is 439 bytes and gets cut off after 257 bytes).
When I inspect the current value of the Text property of said TextBlock right before I change its value through the localization code, it will always have the expected value (not cut off) in either language.
When inspecting the TextBlock at runtime through WPF Inspector it will display the cut off text as the Text property in the second language.
This makes no sense to me at all thus far. But now it gets better.
The original WpfLocalization library reads the localized strings from standard resource files, but we use a modified version that can also read those string from an Excel file. It does that by opening an OleDbConnection using the Microsoft OLE DB driver and reading the strings through that. In the debugger I can see that all the values are read just fine.
Now I was really surprised when a colleague found the fix for the "cut off text" issue. He re-ordered the rows in the Excel sheet. I don't see how that could be relevant, but switching between the two versions of that file has an impact on the issue.

A: That does actually make sense, it's because the ole db driver for Excel has to take a sample of the data in a column to assign it a type and in the case of string, also a length. If it only samples values below the 255 character threshold, you will get a string(255) type and truncated text, if it has sampled a longer string, it will assign it as a memo column and allow longer strings to be retrieved / stored. By re-ordering, you are changing which rows are sampled.
If you read the SQL Server to Excel using oledb you will find this is a known issue. http://msdn.microsoft.com/en-us/library/ms141683.aspx - since you are using the same ole db driver, I would expect the situation to also apply to you.
From the docs:

Truncated text.
  When the driver determines that an Excel column
  contains text data, the driver selects the data type (string or memo)
  based on the longest value that it samples. If the driver does not
  discover any values longer than 255 characters in the rows that it
  samples, it treats the column as a 255-character string column instead
  of a memo column. Therefore, values longer than 255 characters may be
  truncated. To import data from a memo column without truncation, you
  must make sure that the memo column in at least one of the sampled
  rows contains a value longer than 255 characters, or you must increase
  the number of rows sampled by the driver to include such a row. You
  can increase the number of rows sampled by increasing the value of
  TypeGuessRows under the
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel registry
  key. For more information, see PRB: Transfer of Data from Jet 4.0
  OLEDB Source Fails w/ Error.


text:
Q: Why does laravel return an object when filtering against values other than 1? I have the following code:
    $locations = Location::all();
    if ($request->query('customer_id')) {
        return $locations->where('customer_id', $request->query('customer_id'));
    }

    return $locations;

that returns an array if customer_id is 1 and an object if it's anything else. Where is this inconsistency coming from?
If I call flatten() on the result it's always consistent but I can't figure out what causes the difference in results?
Sample output is:
customer_id=1
[
  {
    "id": 2,
    "customer_id": "1",
    "country": "Bulgaria",
    "city": "Sofia",
    "notes": null,
    "created_at": "2019-03-20 08:39:08",
    "updated_at": "2019-03-20 08:39:08",
    "deleted_at": null
  }
]

And if we get the same but customer_id=2 (or any other ID):
{
  "3": {
    "id": 4,
    "customer_id": "3",
    "country": "Bulgaria",
    "city": "Ruse",
    "notes": null,
    "created_at": "2019-03-20 08:39:08",
    "updated_at": "2019-03-20 08:39:08",
    "deleted_at": null
  }
}

A: Try this
$query = Location::query();

if ($request->query('customer_id')) {
    $query =  $query->where('customer_id', $request-customer_id);
}

//you can use another filter if you want. example
if ($request->query('status')) {
    $query =  $query->where('status', 1);
}

$results = $query->get();
return $results;

A: You have an even better way to do the same thing with eloquent way.
 return  Location::
    when($request->query('customer_id'), function($query) use ($request-customer_id) {
              $query->where('customer_id', $request-customer_id);
    })->get()


text:
Q: Could not find andengine.apk? I tried copying some code from one project to another, but on the second project, when I run it, I get the errors:
    [2012-07-09 17:06:34 - AndEngine] Could not find AndEngine.apk!
[2012-07-09 17:06:34 - AndEnginePhysicsBox2DExtension] Could not find AndEnginePhysicsBox2DExtension.apk!

And:

I've read through the numerous suggested solutions and nothing seems to work. So far I have tried deleting the r.java, deleting and reimporting the project, cleaning, refreshing, moving AndEngine's libs folder to the current project, making sure "is library" is unchecked, running  2.2, and using Java 1.6.
Anyone have any other ideas?

A: I'm not very sure of the solution, but here are some suggestions:
Under your library section, there are 2 Xs, which means your project refers to 2 other library projects but cannot find them properly in the path. Try to Add the correct AndEngine or PhysicsBox2D library project path and remove the wrong ones. You will then see a tick rather than an X.
Besides that, it is also possible that your AndEngine or PhysicsBox2D library project is not compiling properly (due to errors or wrong settings). If that is the case, you need to resolve those errors.

Edit 1:
I think the second case I mentioned will not happen:

The picture indicates that even the AndEngine project contains error, the Reference status will still show a tick.
Thus, it is more likely that the path is broken. Since you already added the AndEngine to your current workspace, you might want to try to re-add your Reference Library.

A: Try to add andengine to the build path of your project and launch the project.

A: I am not sure, but in case of third party libs if you get some R.JAVA problem then this problem is related to build path.
So remove all third party jar files again paste it into the root directory and libs of your project. Clean your project, run it. Hope problem will be resolved.


text:
Q: Изменить кодировку cmd при старте jar Делаю консольное приложение, которое получает на вход стороку и фильит, а затем выводит по заданному фильтру соответствующие слова. При двойном клике на jar открывается консоль, и выполняется приложение.
Проблема в том что при выводе результата в кириллице получаеются кракозябры.
Вот пример работы приложения. Помогите исправить:

 public class Grep  {
    private String inputString;
    private String filter;
public Grep(String inputString, String filter) {
        this.inputString = inputString;
        this.filter = filter;
    }

    public String getInputString() {
        return inputString;
    }

    public void setInputString(String inputString) {
        this.inputString = inputString;
    }

    public String getFilter() {
        return filter;
    }

    public void setFilter(String filter) {
        this.filter = filter;
    }

    public void grep() {
        if(getInputString().isEmpty() || getFilter().isEmpty()) {
            System.out.println("Введите данные!");
        } else {
            Stream<String> stringStream = Stream.of(getInputString().split("[\\p{Punct}\\s]+"));
            String result = stringStream.filter(s -> s.contains(getFilter()))
                    .map(String::toLowerCase)
                    .collect(Collectors.joining(", "));
            if(result.isEmpty()) {
                System.out.println("Совпадений не найдено!");
            } else System.out.println(result);

        }

    } }

    public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {

        final String STOP = "stop";
        if (args.length == 0) {
            Process p = Runtime.getRuntime().exec("cmd.exe /c start java -jar " +
                    (new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath())).getAbsolutePath() + " cmd");

        } else {

            while (true) {
                Scanner scanner = new Scanner(System.in);
                System.out.println("Введите слова: ");
                var inputString = scanner.nextLine();
                System.out.println("Введите фильтр: ");
                var filter = scanner.nextLine().toLowerCase();
                Grep grep = new Grep(inputString, filter);
                System.out.print("Результат применения фильтра: ");
                grep.grep();
                System.out.println("Если хотите продолжить нажмите любую клавишу. Введите \"stop\" для выхода.");
                if(scanner.nextLine().equalsIgnoreCase("stop")){
                    scanner.close();
                    System.out.println("Good Bye!");
                    Thread.sleep(2000);
                    System.exit(0);
                }

            }

        }

    }
}

A: Проблема решилась добавление строки  -Dfile.encoding=cp866 в параметры запуска консоли.


text:
Q: Problema en ruta al intentar borrar archivo con UNLIKN en php Hola gente tengo el siguiente problema, necesito borrar un archivo con php, estoy utilizando el comando unlink hasta aquí todo bien , el problema lo tengo a la hora de montar la url con el nombre del archivo como variable, e intentado varios pero sin resultado alguno. La url de mi variable $image_path empieza con public_patch() ya que uso el framework de laravel y la carpeta de imagenes esta dentro de la ruta que me facilita public_path la ruta public se lee correctamente lo que me falla es la variable
Intento 1 url devuelta -> ERROR: unlink(C:\xampp\htdocs\reserva_barcos\public\imagenes\barcos{PRINCIPAL-5fa2c76c0abf0azul-mar-naturaleza-oceano-wallpaper-preview.jpg})
    $imagen_principal = "PRINCIPAL-5fa2c76c0abf0azul-mar-naturaleza-oceano-wallpaper-preview.jpg";

    $image_path = public_path()."\imagenes\barcos\{$imagen_principal}";

    unlink($image_path);

Intento 2 url devuelta -> ERROR: unlink(C:\xampp\htdocs\reserva_barcos\public\imagenes\barcos'PRINCIPAL-5fa2c76c0abf0azul-mar-naturaleza-oceano-wallpaper-preview.jpg')
    $imagen_principal = "PRINCIPAL-5fa2c76c0abf0azul-mar-naturaleza-oceano-wallpaper-preview.jpg";

    $image_path = public_path()."\imagenes\barcos\'$imagen_principal'";

    unlink($image_path);

A: El problema es que la diagonal invertida es un caracter de escape y, por tanto, también debe escaparse para poder usarla en una cadena delimitada por comillas dobles: "\\"
Prueba con:
$imagen_principal = "PRINCIPAL-5fa2c76c0abf0azul-mar-naturaleza-oceano-wallpaper-preview.jpg";
$image_path = public_path()."\\imagenes\\barcos\\{$imagen_principal}";
unlink($image_path);

Importante: En Windows no deberías tener problemas con esto, pero, en ambientes LINUX debes usar / o, en todo caso, la constante DIRECTORY_SEPARATOR para evitar cualquier problema.


text:
Q: Handling external requests from Backend and sharing to mobile app I've an Android app made on Xamarin .net 2.1 standard and a backend (REST API using .net6 and MySQL). From an architecture perspective, I don't know what is the best option so I ask for your help.
At this moment, from mobile app every time a user refreshes Dasboard Page, backend do rest call over https to an external endpoint to retrieve json, then do some calculations data and send back to mobile so user can see data updated (it's binance api call to obtain btc ptice in usdt and eur).
As this is a very bad idea when goes into production, I'm thinking how to solve it. My main idea, is creating console app that proactively does that call every 5 seconds and save it somewhere (may saving to file can cause lots disk access hahaha). At the end that data collected must be shared in some efficient way so mobile can fetch that data... What you think could be the best approach? I know that I can stream that values from Binance using Websockets but can't see clear what's best choice and how to connect to mobile. Thanks all!

A: First of all if you are working on a financial project you should know that each second is important , so the idea of getting data every 5 seconds is not a good idea, so let's go to explain a better way :
As you said and is obvious the best way in this situation is to get your data from webSocket because it's real-time and it's so reliable and you are always update.
But there is a problem and that's there are lots of data sending to you, so you should be able to handle it. to handle this volume of data, the best offer is to use JAVA and it's frameworks like Spring.
So this was one part of problem now let's go to the second part.
what should you do with these data ?? where should you persist them ??
As you maybe noticed before, your data is a time-based data.
When it comes to time-based data , the best choice is : Postgres timescale DB.
Install a Postgres and create a database then apply timescale DB plugin on your database.
Now every thing is ready, create a time-based table in your timescale db .
Now persist price of each seconds on it.
each time your front-end refreshed the page just select from your table ((time based select is highly optimized in Postgres timescale DB, even in large amount of records )) and return the last price to it. Beside that you have the price of each moment.
Even you can stream the data to your front-side too.
Feel free to ask any question you need to know.


text:
Q: Erro ao inserir dados no MYSQL com PYTHON Estou fazendo um trabalho na faculdade de uma fechadura eletronica e no momento estou criando um historico em um banco de dados MYSQL das tags lidas e a quem elas pertencem ou não. O problema no codigo é que ao executar ele não da erro algum, porem ele só contabiliza na coluna ID_evento (esta com auto incremento) e não apresenta informação alguma na tabela, fica invisivel as informações inseridas pelo python, mas ao executar a mesma query direto no SQL aparece normal e com o ID_evento respectivo a como se estivesse executado a query no python.
import string
import pymysql as sql

con = sql.connect(host='localhost',
                    user='root',
                    password='root',
                    db='rfid_teste',
                    charset='utf8mb4',
                    cursorclass=sql.cursors.DictCursor)
c = con.cursor()

query = 'SELECT NOME_USUARIO FROM rfid_teste WHERE TAG = "332b7b06"'
c.execute(query)
resultado = c.fetchone()
resultado_t = str(resultado)
sql_nome = resultado_t[18:25] #aqui sai o nome 'matheus'
sql_tag = 254145
query_i = "INSERT INTO registro (usuario, tag, data, hora) VALUES (%s, %s, CURRENT_DATE(), CURRENT_TIME() );"
c.execute(query_i, (sql_nome, sql_tag))
teste = (c.execute(query_i, (sql_nome, sql_tag)))
print (teste) #aqui retorna 1 não sei porque

A: Descobri o erro, faltava um commit após a execução da query.
No meu caso ficou assim:
c.execute(query_i, (sql_nome, sql_tag))
con.commit()```

A partir daí inseriu o dado.


text:
Q: how to make ensure one active session per one user using python flask? how to make ensure one active session per one user using python flask?
Description: if one user logged in two different machines with same credentials
I want  mechanism to force logout earlier active sessions of that user with flask and python. Please help me out in this.
I am currently using flask-login, load_user() and login_manager libraries for login mechanism.

A: One way for ensuring this would be by generating a session id from server. You would need to generate a unique session id every time a user logs in and store it in some database against that user. Apart from this you would need to authenticate user every time an endpoint call, which requires user to be logged in, is made. And of course discard the session id on logout.
This way whenever a user logs in the old session id is discarded and the previous session no more remains valid.


text:
Q: Слияние многосегментных временных рядов при помощи pandas.merge_asof() Есть два набора данных:

*

*Набор ежедневных значений множества однородных объектов (много клиентов и их транзакции, много магазинов и их ежедневные продажи). Они организованные в длинную таблицу так, что для каждого объекта записаны значения на каждый день в масштабе двух лет (2020-21 года). В данных есть пропуски некоторых дат, когда объект переезжал с места на место, был сломан и т.д.

*Набор свойств каждого объекта с временной меткой, когда эти свойства были обновлены для 20-21 годов. Свойства такого характера: адрес, регион, тип учреждения, где объект находится и т.д. Как только объект куда-то переезжает, появляется новая запись с новым значением одного или нескольких свойств и временем обновления.
Есть задача, примерджить справа датафрейм 2 к датафрейму 1 так, чтобы на каждом участке ежедневного временного ряда кроме самих значений были актуальные на данный период свойства.
Я надеялся использовать
pd.merge_asof(left=df1.sort_values(by=['object_id', 'date']),
              right=df2.sort_values(by=['object_id', 'date'],
              on='object_id', by='date', direction='forward')

Однако на выходе получились данные размером df1, где все поля свойств имель значения NaN.


text:
Q: How to find blob in tree by its name I have a tree of commit found by SHA-1,code is:
tree = repo.tree(sha)
now I need to find blob by file name and display its content

A: given the SHA1 of the commit itself, you would:
git show SHA1:path/to/your/file.txt

if you know the sha1 of the blob itself, you can
git cat-file blob SHA1


text:
Q: Do non-Elven blades damage the Nazgûl despite being destroyed? As I understand it (correct me if this is wrong) swords not crafted by elves are destroyed upon striking a Nazgûl- but do they do any damage to him (it?) in the process?

A: I will correct you:

"Look!" he cried; and stooping he lifted from the ground a black cloak that had lain there hidden by the darkness. A foot above the lower hem there was a slash. "This was the stroke of Frodo's sword," he said. "The only hurt that it did to his enemy, I fear; for it is unharmed, for all blades perish that pierce that dreadful King. More deadly to him was the name of Elbereth." - Aragorn, "Flight to the Ford," Fellowship of the Ring, p.201

It is unclear if "that dreadful king" is limited to the Witch King or the Nazgûl more generally (who had all been, at least, Lords in life).
Notwithstanding, there is no indication that:

*

*Only elven blades can wound Nazgûl; Frodo's blade, like Merry's subsequently, was a product of Westernesse (either in Númenor or in exile is not revealed). In addition, there is no hint that Eowyn's blade, which I recall caused some inconvenience to the Witch King, was anything other then the product of Rohan.

*That elven blades would survive; Aragorn is quite clear: "... all blades perish ...".

A: I think that there seem to be instances where it appears the Nazgul can be hurt by ordinary weapons. There is a passage concerning a Dunedan, "Boromir was a great captain and even the Witch-king feared him." [Appendix A: The Stewards] Why the fear? There is also another passage in which he no longer takes heed of missiles. If they could not hurt him, why does the WK heed them in the first place?

"Over the hills of slain a hideous shape appeared: a horseman, tall,
  hooded, cloaked in black. Slowly, trampling the fallen, he rode forth,
  heeding no longer any dart. He halted and held up a long pale sword.
  And as he did so a great fear fell upon all, defender and foe alike;
  and the hands of men dropped to their sides, and no bows sang. For a
  moment all was still."

There is also an instance during the Battle of Pelennor where he was pierced by Merry's blade, the one Tom Bombadil got for him at the Barrow-downs.

Merry's sword had stabbed him from behind, shearing through the black
  mantle, and passing up beneath the hauberk has pierced the sinew
  behind his mighty knee. [Battle of the Pelennor Fields]

A little while later in the narrative a brief history of the sword is given:

So passed the sword of the Barrow-downs, work of Westernesse. But glad
  would he have been to know its fate who wrought it slowly long ago in
  the North-kingdom when the Dúnedain were young, and chief among their
  foes was the dread realm of Angmar and its sorcerer king. [Battle of
  the Pelennor Fields]

Here there is a blade that was made slowly in the kingdom of Arnor for dealing with their enemy from Angmar. Many years later it is taken from the Barrow-downs and it does damage to the Witch-king. There is also Éowyn's sword not made by the Dúnedain;

she drove her sword between crown and mantle, as the great shoulders
  bowed before her. The sword broke sparkling into many shards. The
  crown rolled away with a clang. Éowyn fell forward upon her fallen
  foe. But lo! the mantle and hauberk were empty. [Battle of the
  Pelennor Fields]

A: At least one sword, made by Men, was able to hurt the Nazgûl:
ROTK, Book V, Ch. 6 The Battle of the Pelennor Fields:

    And still Meriadoc the hobbit stood there blinking through his tears,
  and no one spoke to him, indeed none seemed to heed him. He brushed
  away the tears, and stooped to pick up the green shield that Éowyn had
  given him, and he slung it at his back. Then he looked for his sword
  that he had let fall; for even as he struck his blow his arm was
  numbed, and now he could only use his left hand. And behold! there lay
  his weapon, but the blade was smoking like a dry branch that has been
  thrust in a fire; and as he watched it, it writhed and withered and
  was consumed.     So passed the sword of the Barrow-downs, work of
  Westernesse. But glad would he have been to know its fate who wrought
  it slowly long ago in the North-kingdom when the Dúnedain were young,
  and chief among their foes was the dread realm of Angmar and its
  sorcerer king. No other blade, not though mightier hands had wielded
  it, would have dealt that foe a wound so bitter, cleaving the undead
  flesh, breaking the spell that knit his unseen sinews to his will.


text:
Q: .Net standard library that supports XPath 3.1 I'm maintaining a legacy tool of the company I work for written in C# and I'm converting it to .Net standard 2.0. It uses the Saxon-HE processor to process some XPaths and replace some configurations in files.
Its NuGet package on .NET has dependencies that do not allow the execution on all the .Net standard 2.0 compliant platforms (in my case both .Net Framework and .Net core), so I need to replace it with one another tool, better if the standard .Net XPath library.
The problem is that the tool uses some XPaths that perform complex operations such as concatenate strings and select an array item, and I don't know if it's a Saxon-specific syntax or regards a standard.
It is important to know this because if the XPaths are compliant to some XPath standard I could find one another way to process the same XPaths.
Here is some examples:
First:
for $row in /Item/SubItem[*]/SubSubItem return(concat($row, \"/ConcatValue\"))

Second:
/Item/SubItem[*]/SubSubItem/(add[@key=\"TheKey\"]/@value/string(), '')[1]

Do you know something about this XPath syntax?
Thank you

A: The XPath expressions you have given as examples require an XPath 2.0 processor but they are not specific to Saxon.
The expression
for $row in /Item/SubItem[*]/SubSubItem return(concat($row, \"/ConcatValue\"))

is a ForExpression, which is specific to XPath 2.0, and is not easily converted to XPath 1.0 because its result is a sequence of strings, and there is no such data type in XPath 1.0.
The expression
/Item/SubItem[*]/SubSubItem/(add[@key=\"TheKey\"]/@value/string(), '')[1]

is specific to XPath 2.0 because it uses a parenthesized expression on the RHS of the "/" operator; and again, because it returns a sequence of strings.
I'm afraid I can't advise you whether there exist XPath 2.0 libraries that run on .NET Core, which I assume is your requirement. Saxon cannot be made to run on .NET Core because of its dependency on IKVM, which doesn't support that platform and which (I gather) cannot readily be adapted to do so.
Note that XPath 2.0 is a subset of XQuery 1.0, so you could extend your search to XQuery 1.0 processors as well as XPath 2.0 processors.

A: Thanks to this comment I was able to test XPath2.Net and now everything works. I needed to change only one type of XPath definition
This one:
/Item/SubItem[*]/SubSubItem/(add[@key=\"TheKey\"]/@value/string(), '')[1]

Changes to
/Item/SubItem[*]/SubSubItem/(add[@key=\"TheKey\"]/@value/string(.), '')[1]

Please note the additional dot argument of the string() function.
This is strange as it should not be require the dot; in fact, per standard

In the zero-argument version of the function, $arg defaults to the
  context item. That is, calling fn:string() is equivalent to calling
  fn:string(.)

but XPath2 complains with this error
{"The function 'string'/0 was not found in namespace 'http://www.w3.org/2003/11/xpath-functions'"}

UPDATE:
After updating the XPath2.Net library to version 1.0.8 the string() syntax works.


text:
Q: Shares endpoint on LinkedIn API not working The endpoint to get shares by owner is not working for me.
This is the full URL I'm using:
https://api.linkedin.com/v2/shares?q=owners&owners=urn:li:organization:{ID}

But I receive this error:
{"serviceErrorCode":0,"message":"Invalid query parameters passed to request","status":400}

I know the access token I'm using is working, if I try to get one share by ID the response is a success, using the following URL:
https://api.linkedin.com/v2/shares/urn%3Ali%3Ashare%3A{ID}

Am I doing something wrong? For me this error looks like a bug in the API


text:
Q: WPF/XAML event handler binding in style with view model I created my calendar with style:
<Style x:Key="CalendarDayButtonStyle" TargetType="CalendarDayButton">
        <Setter Property="Background" Value="{StaticResource Brush.Foreground.TextBlock.LightBlue}" />
        <Setter Property="MinWidth" Value="5" />
        <Setter Property="MinHeight" Value="5" />
        <Setter Property="FontSize" Value="12" />
        <Setter Property="HorizontalContentAlignment" Value="Center" />
        <Setter Property="VerticalContentAlignment" Value="Center" />
        <Setter Property="Template">
        ...

        <EventSetter Event="MouseDoubleClick" Handler="{Binding DayButtonCommand}"/>
    </Style>

and I want to perform the command by MouseDoubleClick Event.
But at the start of the application exception occurs:
"An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: BaseUri can be set only once at the root node (the XamlXmlReader possibly a default value is provided at the root node)."
I create this Style in resource file and work with MVVM.
How can I bind MouseDoubleClick event with this Style for CalendarDayButton?
Thanks.

A: You shouldn't use a style for this but rather use an attached behavior to fire a command when the Double Click event is fired. MVVM light has such a feature.
The XAML looks like this :
<CalendarDayButton ...>

   <i:Interaction.Triggers>
      <i:EventTrigger EventName="Tap">
        <command:EventToCommand
            Command="{Binding Main.NavigateToArticleCommand,
            Mode=OneWay,
            Source={StaticResource Locator}}"
            CommandParameter="{Binding Mode=OneWay}" />
      </i:EventTrigger>
   </i:Interaction.Triggers>
 </CalendarDayButton>

EDIT : you can also use a Routed EventHandler on the Calendar object in the View, and call the ViewModel command from the view's codebehind. Example


text:
Q: Add markers to leaflet issue It's very likely a stupid error here - but I can't find it: my markers simply won't show up.. Anyone a clue what's wrong? There are no errors in the chrome developer console (live webpage with the below piece of code here: https://gimoya.github.io/elba_trails/map.html).
/*
Points of interest
*/

var POIs = {
    "type": "FeatureCollection",
    "name": "POIs",
    "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
    "features": [
        { "type": "Feature", "properties": { "name": "Calendozio Minen", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.433195000778694, 42.846563435712767 ] } },
        { "type": "Feature", "properties": { "name": "Bar & Crepes 'I Sassirossi'", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.421687105111864, 42.859251223462977 ] } },
        { "type": "Feature", "properties": { "name": "Bar & Ristorante 'La Piazza'", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.401553011790016, 42.813766757348091 ] } },
        { "type": "Feature", "properties": { "name": "Aloe B & B Ranch Elba", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.408682377036765, 42.811250255377345 ] } },
        { "type": "Feature", "properties": { "name": "PP 'Le Panche'", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.393229679804257, 42.808642183011926 ] } },
        { "type": "Feature", "properties": { "name": "Ristorante Mare - Magazzini", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.358303702245937, 42.799840744001706 ] } },
        { "type": "Feature", "properties": { "name": "Bar Ristorante Le Palme - Bagnaia", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.36372817884163, 42.810643588703883 ] } },
        { "type": "Feature", "properties": { "name": "Bar & Stabilimento Mandel", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.372453924676392, 42.732403377493846 ] } },
        { "type": "Feature", "properties": { "name": "Minimarkt Lacona & Bankomat", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.313554269928702, 42.765188059048825 ] } },
        { "type": "Feature", "properties": { "name": "'Tratoria Orti di Mare'", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.309327836357474, 42.764830547047488 ] } },
        { "type": "Feature", "properties": { "name": "Ristorante Cacio & Vino", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.211601766564495, 42.751601080030852 ] } },
        { "type": "Feature", "properties": { "name": "Bar Spiaggia Cavolli", "description": null }, "geometry": { "type": "Point", "coordinates": [ 10.186399316735942, 42.73738496151384 ] } },
        { "type": "Feature", "properties": { "name": "Minimarkt Seccheto", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.176845708130028, 42.73769072758364 ] } },
        { "type": "Feature", "properties": { "name": "Panificcio Seccheto", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.177415675024058, 42.737597700262853 ] } },
        { "type": "Feature", "properties": { "name": "Baba Pizza Pomonte", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.1208601, 42.7486187 ] } },
        { "type": "Feature", "properties": { "name": "Mini Market Pomonte", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.121819933812914, 42.748386473414676 ] } },
        { "type": "Feature", "properties": { "name": "Hotel & Bar Il Perseo Chiessi", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.113424194143604, 42.759005039240684 ] } },
        { "type": "Feature", "properties": { "name": "Hotel & Bar Bel Mare Patresi \/ Bike Guide Matteo Anselmi", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.117820207820397, 42.791279815618402 ] } },
        { "type": "Feature", "properties": { "name": "Osteria Del Noce", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.167205994929112, 42.790316468951815 ] } },
        { "type": "Feature", "properties": { "name": "Pizzeria & Bar Bagni Paola Procchio", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.247504370542897, 42.789433590132184 ] } },
        { "type": "Feature", "properties": { "name": "Osteria Locanda Cecconi Porto Azzurro", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.398243648910684, 42.765950601670468 ] } },
        { "type": "Feature", "properties": { "name": "Pizzeria Da Giuseppe", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.395422349335403, 42.765225325040845 ] } },
        { "type": "Feature", "properties": { "name": "Bar Alta Luna Porto Azzurro", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.398409293393327, 42.765735721919597 ] } },
        { "type": "Feature", "properties": { "name": "Il Veliero Bar Marina di Campo", "description": "Goolge Maps Search<\/a>" }, "geometry": { "type": "Point", "coordinates": [ 10.236144660833816, 42.742844995518332 ] } }
    ]
}

for (i = 0; i < POIs.features.length; i++) {
    new L.marker( POIs.features[i].geometry.coordinates )
            .bindTooltip('
'+POIs.features[i].properties.name+'
'+POIs.features[i].properties.description,
                {
                    permanent: false,
                    direction: 'right'
                }
            )
            .addTo(map);
    }

A: Not sure why it does not work for you. I used your code and it seems to be working fine for me. Here is a working example:
Edit: According to Kay it seems that the issue was the fact that the xy-coordinates were swapped in his example.

<!DOCTYPE html>

  <title>Quick Start - Leaflet</title>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />


text:
Q: Enable session_state parameter in authentication response - Keycloak 18.0.0 The session_state parameter which used to be present in the authentication/ token response is not present in keycloak version 18.0.0 along with the refresh_token. Although there is an option under Clients -> OpenID Connect Compatibility Modes to exclude/include this, that doesn't seem to do anything.
We're using this value in our application hence with the upgrade to keycloak 18.0.0 the authentication flow seem to be broken.
Is there any way we can include this parameter in the authentication response?


text:
Q: Autenticação Windows A minha autenticação do Windows esta se perdendo com o tempo.
Faço a seguinte validação:
if(HttpContext.Current.User.Identity.IsAuthenticated == true)
    dsHostName = User.Identity.Name.Split('\\')[1].ToString();

-Authentication IIS
Anonimo: Desabilitado
Windows: Habilitado
No primeiro acesso faz a autenticação, quero força a autenticação quando se perder, conforme a imagem abaixo:


text:
Q: Java threading, a consumer dont want to end Why does my Thread (Runnable) not get off the run() method once it reaches end of the block?
This is the code:
//1 Entry point for thread with run method
public void run() {
    System.out.println("Hashmaker():/run(). " + threadName + " Running "  );
    try {
        String original = in;
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(original.getBytes());
        byte[] digest = md.digest();
        StringBuffer sb = new StringBuffer();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
            System.out.println("Hashmaker:/run(). original: " + original);
            System.out.println("Hashmaker:/run(). digested(hex):" + sb.toString());
            //src http://www.avajava.com/tutorials/lessons/how-do-i-generate-an-md5-digest-for-a-string.html
        }
            // Let the thread sleep for a while.
            //Thread.sleep(7);
            System.out.println("Hashmaker:/run(). Thread: " + threadName + " recieved a clear password = " + in);
            //Save the hash
            hash=sb.toString();
    }
    /*catch (InterruptedException e) {
        System.out.println("Hashmaker:/run(). Thread " +  threadName + " interrupted.");
    } */
    catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Hashmaker:/run(). Thread " +  threadName + " exiting.");
}

It is ideally supposed to end normally, then my main() method would start other stuff:
public static void main(String[] args) throws Exception {
    //Parse the args
    if (args.length != 1) {
        System.err.println("Main()/: String to MD5 digest should be first parameter\n");
        System.out.println("Main()/: Require now a clear password with 4 char :");
        sc = new Scanner(System.in);
        in = sc.nextLine();
        force = 2;
    }
    else{
        in = args[0];
        force = Integer.parseInt(args[1]);
    }
    //Set the count of Breakers
    count=force;
    //Make the hash
    Hashmaker hm = new Hashmaker(in,"Hashmaker");
    hm.start();
    System.out.println("Main()/: Managing the breakers will start !");

    //Get the hash
    hash=hm.getHash();
    //Manage the Breakers
    f = new File(count);
    for(int i=0; i<count;i++){
        Hashbreaker hb = new Hashbreaker(hash,"HashBreaker"+i);
        f.enfiler(hb);
        hb.start();
    }
}

THE NORMAL SCENARIO TO ME, IS: create and start a thread to generate a digest MD5 hash, get the hash, feed consumer thread with it and bruteforce it till one bruteforce hash give a "compareTo" secret hash == 1.


text:
Q: Filter out / hide OR replace excel dax measure 0 values I have the following dax measure in the value area of a pivot table to return a concatenated list of unique values from a table:
=CONCATENATEX(
    Values(
    Table1[Column2]
    ),
    Table1[Column2],", "
)

There are instances where 0 is returned as the value because no corresponding values exists for that row in the source data.
Is it possible to either replace with "-" or preferrably hide or filter out these rows entirely.
Any ideas?


text:
Q: Rendering partial with remote: true if i have few same ids I have a problem with rendering data on my page through remote: true.
I have a comments and subcomments (comments to the comments). When I click "Comment" button under the second Post, a comment appears below the first because I have a few same ids "comment-list" in my loop. How I should fix this? P.S Sorry for my english :)
Here is how look my Post and Comments form:
<% @posts.each do |post| %>

  ...
  <% if current_user == post.user %>
    <%= link_to "delete", post, method: :delete, remote: true %>
  <% end %>

  <%= render partial: 'post_comments/comments', locals: { post: post } %>

<% if user_signed_in? %>

    <%= render partial: 'post_comments/new_comment_form', locals: { post: post } %>

<% end %>

And here is how looks my create.js.erb
$('#comments-list').html("<%= j (render partial: 'post_comments/comments', locals: { post: @post }) %>");

A: What I've done in a similar situation is make your div IDs specific to each post:
<div id="comments-list-<%= @post.id.to_s %>">

and then in your jquery code specify the relevant post:
$('#comments-list-<%= @post.id.to_s %>').html("<%= j (render partial: 'post_comments/comments', locals: { post: @post }) %>");

A: *

*Let create a wrapper specifying your post
<% @posts.each do |post| %>
  <div id="post_<%= post.id %>">

<% end %>

*Use comments-list as class instead (the same apply for comment-form)

  <%= render partial: 'post_comments/comments', locals: { post: post } %>

*Finally your jquery selector in erb will be:
$("#post_<%= @post.id %> .comments-list")


text: Q: Why this :$I(x)=\int_{-x}^x {0.5(\exp({-t² {\operatorname{erf}(t^2)}})}dt$ is not error function for $|x| >3$? This integral : $$I(x)=\int_{-x}^x {0.5(\exp({-t² {\operatorname{erf}(t^2)}})}dt$$ close to $x$ for $|x|<3$ and converge to $1$ for $|x|>3$  from $-\infty \to +\infty$  as shown here such that concide with error function for that large range over Real number , Now my question here is it possible to consider  that distribution as  Gausse distribution for $|x|>3$ since there is a concidence ?


text:
Q: creating jenkins container by docker I wanna create jenkins container by docker.
what I have done is
1.create jenkins container by Kitematic.
2.unlock jenkins
3.customize  jenkins (install suggest plugin)
4.Create First Admin User
stock here after input username and password
here is the exception.
btw.
1.this happened when I create jenkins for the second time.
The first time is ok without exception.
2.if I don`t install any plugin , it will run without exception.
https://imgur.com/a/xWIUo

INFO: Completed initialization Nov 02, 2017 6:11:44 AM
  hudson.PluginManager dynamicLoad INFO: Plugin email-ext:2.61
  dynamically installed Nov 02, 2017 6:11:44 AM
  hudson.model.UpdateCenter$DownloadJob run INFO: Installation
  successful: Email Extension Plugin Nov 02, 2017 6:11:44 AM
  hudson.model.UpdateCenter$DownloadJob run INFO: Starting the
  installation of Mailer Plugin on behalf of admin Nov 02, 2017 6:11:44
  AM hudson.model.UpdateCenter$InstallationJob _run INFO: Skipping
  duplicate install of: Mailer Plugin@1.20 Nov 02, 2017 6:11:44 AM
  hudson.model.UpdateCenter$DownloadJob run INFO: Installation
  successful: Mailer Plugin Nov 02, 2017 6:13:07 AM
  hudson.init.impl.InstallUncaughtExceptionHandler$1 reportException
  WARNING: null java.io.IOException: finished at
  com.jcraft.jzlib.DeflaterOutputStream.write(DeflaterOutputStream.java:90)
  at java.io.FilterOutputStream.write(FilterOutputStream.java:97) at
  org.kohsuke.stapler.compression.FilterServletOutputStream.write(FilterServletOutputStream.java:26)
  at
  hudson.util.HttpResponses$JSONObjectResponse.generateResponse(HttpResponses.java:181)
  at
  org.kohsuke.stapler.HttpResponseRenderer$Default.handleHttpResponse(HttpResponseRenderer.java:124)
  at
  org.kohsuke.stapler.HttpResponseRenderer$Default.generateResponse(HttpResponseRenderer.java:69)
  at org.kohsuke.stapler.Function.renderResponse(Function.java:136) at
  org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:119)
  at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:129) at
  org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
  at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:715) at
  org.kohsuke.stapler.Stapler.invoke(Stapler.java:845) at
  org.kohsuke.stapler.MetaClass$3.doDispatch(MetaClass.java:209) at
  org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
  at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:715) at
  org.kohsuke.stapler.Stapler.invoke(Stapler.java:845) at
  org.kohsuke.stapler.Stapler.invoke(Stapler.java:649) at
  org.kohsuke.stapler.Stapler.service(Stapler.java:238) at
  javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at
  org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)
  at
  org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
  at
  hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:135)
  at jenkins.install.SetupWizard$1.doFilter(SetupWizard.java:530) at
  hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:132)
  at
  hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:138)
  at
  org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
  at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:80) at
  org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
  at
  hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
  at
  hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51)
  at
  hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
  at
  jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117)
  at
  hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
  at
  org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
  at
  hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
  at
  org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:142)
  at
  hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
  at
  org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
  at
  hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
  at
  jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:92)
  at
  hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
  at
  org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
  at
  hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
  at
  hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
  at
  hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:90)
  at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171) at
  org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
  at
  org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
  at
  org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
  at
  hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)
  at
  org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
  at
  org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
  at
  org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
  at
  org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
  at
  org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
  at
  org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:553)
  at
  org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
  at
  org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
  at
  org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
  at
  org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
  at
  org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
  at
  org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
  at
  org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
  at org.eclipse.jetty.server.Server.handle(Server.java:499) at
  org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311) at
  org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
  at
  org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
  at
  winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  at java.lang.Thread.run(Thread.java:748)

A: I have ever faced the same issue like you when i deploy container in docker swarm when i choose Install suggested plugins, but try to choose Select plugins to install, it works for me


text:
Q: Substitute a function with the preprocessor I must do a horrible thing, i.e. automatically substitute a function call with a different function call, with different number of parameters, at precompilation time.
Example:
#include <iostream>

int FuncToChange(void* a, int b, void* c, int d) {
   return 0;
}

int NewFunc(void* a, void* c, int d) {
   return 1;
}

#define FuncToChange($1, $2, $3, $4) NewFunc($1, $3, $4)

int main()
{
   int a = 1, b = 2, c = 256;

   int v = FuncToChange(&a + 1, c + 1, &b, 2*c);
}

This code works, i.e. in main() NewFunc() is called instead of FuncToChange().
Now I would like to remove that #define (the reason is that I cannot modify the code), and obtain the same result setting the IDE's build options.
The IDE is CodeBlocks 10.05.
I already tried to add what follows to Project / Project Build Options / Compiler Settings / #define:
NewFunc($1, $3, $4)=FuncToChange($1, $2, $3, $4)

but nothing changed. Does anybody have any idea?
Thank you in advance!
Pietro
Platform:
GCC/MinGW
Windows7 64 bit

Reason behind this question:
I have to port an Excel plugin from XP 32 bit to Windows 7 64 bit. The plugin has been developed with CodeBlocks, and I cannot change tool set. The file FRAMEWRK.C (part of "2010 Office System Developer Resources", Excel2010 XLL SDK) has evolved, and now uses calls to non standard functions such as memcpy_s(), not available in MinGW. So, with the preprocessor, I substitute memcpy_s() with memcpy(), taking care of the different parameters.

A: Ok. I moved the #define in its own include file. Then I specified it to GCC, with the -include command line option.
Doing so, the file is included at the top of every source file.


text:
Q: regex search in datatables that is connected to a database I am trying to be able to a regex search in datatables that is connected to a database.
The code I have currently handles searching(see 3 below):
if( !empty($requestData['search']['value']) ) {
    // if there is a search parameter
    $sql = "SELECT first_name, last_name, position, office, start_date, salary";
    $sql.=" FROM $table";
    $sql.=" WHERE first_name LIKE '%".$requestData['search']['value']."%' ";    // $requestData['search']['value'] contains search parameter
    $sql.=" OR last_name LIKE '%".$requestData['search']['value']."%' ";
    $sql.=" OR position LIKE '%".$requestData['search']['value']."%' ";
    $sql.=" OR office LIKE '%".$requestData['search']['value']."%' ";
    $sql.=" OR start_date LIKE '%".$requestData['search']['value']."%' ";
    $sql.=" OR salary LIKE '%".$requestData['search']['value']."%' ";

    $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees-456");
    $totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result without limit in the query

    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."   LIMIT ".$requestData['start']." ,".$requestData['length']."   "; // $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc , $requestData['start'] contains start row number ,$requestData['length'] contains limit length.
    $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees-789"); // again run query with limit

} else {

    $sql = "SELECT first_name, last_name, position, office, start_date, salary";
    $sql.=" FROM $table";

    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."   LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
    $query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees 000");

}

What I want to be able to do is do a regex accross the data (see 2 below).How would I write the above code to do this?
I have tried this (replaced LIKE with REGEXP and removed the %) but can not get it to work, which i am beginnig to wonder if there is more to it?
$sql = "SELECT first_name, last_name, position, office, start_date, salary";
$sql.=" FROM $table";
$sql.=" WHERE first_name REGEXP '".$requestData['search']['value']."' ";    // $requestData['search']['value'] contains search parameter
$sql.=" OR last_name REGEXP '".$requestData['search']['value']."' ";
$sql.=" OR position REGEXP '".$requestData['search']['value']."' ";
$sql.=" OR office REGEXP '".$requestData['search']['value']."' ";
$sql.=" OR start_date REGEXP '".$requestData['search']['value']."' ";
$sql.=" OR salary REGEXP '".$requestData['search']['value']."' ";

1 - This is my dataset:
mysql> SELECT * FROM datatables_demo;                                           +----+------------+-----------+-------------+--------+------------+--------+
| id | first_name | last_name | position    | office | start_date | salary |
+----+------------+-----------+-------------+--------+------------+--------+
|  1 | Tiger      | Nixon     | Accountant  | Tokyo  | 2016-11-08 | 320800 |
|  2 | Garrett    | Winters   | Accountant2 | Tokyo  | 2016-11-08 | 170750 |
|  3 | Ashton     | Cox       | Accountant3 | Tokyo  | 2016-11-08 |  86000 |
|  4 | Cedric     | Kelly     | Accountant4 | Tokyo  | 2016-11-08 | 433060 |
|  5 | Tiger5     | Nixon     | Accountant  | Tokyo  | 2016-11-08 | 320800 |
+----+------------+-----------+-------------+--------+------------+--------+
5 rows in set (0.00 sec)

2 - This is a regex example:
mysql> SELECT first_name, last_name, position, office, start_date, salary FROM datatables_demo WHERE first_name REGEXP '^[TG]';
+------------+-----------+-------------+--------+------------+--------+
| first_name | last_name | position    | office | start_date | salary |
+------------+-----------+-------------+--------+------------+--------+
| Tiger      | Nixon     | Accountant  | Tokyo  | 2016-11-08 | 320800 |
| Garrett    | Winters   | Accountant2 | Tokyo  | 2016-11-08 | 170750 |
| Tiger5     | Nixon     | Accountant  | Tokyo  | 2016-11-08 | 320800 |
+------------+-----------+-------------+--------+------------+--------+
3 rows in set (0.00 sec)

3 - This is a regular search example:
mysql> SELECT first_name, last_name, position, office, start_date, salary FROM datatables_demo WHERE first_name LIKE '%ti%';
+------------+-----------+------------+--------+------------+--------+
| first_name | last_name | position   | office | start_date | salary |
+------------+-----------+------------+--------+------------+--------+
| Tiger      | Nixon     | Accountant | Tokyo  | 2016-11-08 | 320800 |
| Tiger5     | Nixon     | Accountant | Tokyo  | 2016-11-08 | 320800 |
+------------+-----------+------------+--------+------------+--------+
2 rows in set (0.01 sec)


text:
Q: How to make binary distribution of Qt application for Linux I am developing cross-platform Qt application.
It is freeware though not open-source. Therefore I want to distribute it as a compiled binary.
On windows there is no problem, I pack my compiled exe along with MinGW's and Qt's DLLs and everything goes great.
But on Linux there is a problem because the user may have shared libraries in his/her system very different from mine.
Qt deployment guide suggests two methods: static linking and using shared libraries.
The first produces huge executable and also require static versions of many libraries which Qt depends on, i.e. I'll have to rebuild all of them from scratches. The second method is based on reconfiguring dynamic linker right before the application startup and seems a bit tricky to me.
Can anyone share his/her experience in distributing Qt applications under Linux? What method should I use? What problems may I confront with? Are there any other methods to get this job done?

A: When we distribute Qt apps on Linux (or really any apps that use shared libraries) we ship a directory tree which contains the actual executable and associated wrapper script at the top with sub-directories containing the shared libraries and any other necessary resources that you don't want to link in.
The advantage of doing this is that you can have the wrapper script setup everything you need for running the application without having to worry about having the user set environment variables, install to a specific location, etc. If done correctly, this also allows you to not have to worry about from where you are calling the application because it can always find the resources.
We actually take this tree structure even further by placing all the executable and shared libraries in platform/architecture sub-directories so that the wrapper script can determine the local architecture and call the appropriate executable for that platform and set the environment variables to find the appropriate shared libraries. We found this setup to be particularly helpful when distributing for multiple different linux versions that share a common file system.
All this being said, we do still prefer to build statically when possible, Qt apps are no exception. You can definitely build with Qt statically and you shouldn't have to go build a lot of additional dependencies as krbyrd noted in his response.

A: sybreon's answer is exactly what I have done. You can either always add your libraries to LD_LIBRARY_PATH or you can do something a bit more fancy:
Setup your shipped Qt libraries one per directory. Write a shell script, have it run ldd on the executable and grep for 'not found', for each of those libraries, add the appropriate directory to a list (let's call it $LDD). After you have them all, run the binary with LD_LIBRARY_PATH set to it's previous value plus $LDD.
Finally a comment about "I'll have to rebuild all of them from scratches". No, you won't have to. If you have the dev packages for those libraries, you should have .a files, you can statically link against these.

A: Not an answer as such (sybreon covered that), but please note that you are not allowed to distribute your binary if it is statically linked against Qt, unless you have bought a commercial license, otherwise your entire binary falls under the GPL (or you're in violation of Qt's license.)
If you have a commercial license, never mind.
If you don't have a commercial license, you have two options:

*

*Link dynamically against Qt v4.5.0 or newer (the LGPL versions - you may not use the previous versions except in open source apps), or

*Open your source code.

A: Shared libraries is the way to go, but you can avoid using LD_LIBRARY_PATH (which involves running the application using a launcher shell script, etc) building your binary with the -rpath compiler flag, pointing to there you store your libraries.
For example, I store my libraries either next to my binary or in a directory called "mylib" next to my binary. To use this on my QMake file, I add this line in the .pro file:
QMAKE_LFLAGS += -Wl,-rpath,\\$\$ORIGIN/lib/:\\$\$ORIGIN/../mylib/

And I can run my binaries with my local libraries overriding any system library, and with no need for a launcher script.

A: You can also distribute Qt shared libraries on Linux. Then, get your software to load those instead of the system default ones. Shared libraries can be over-ridden using the LD_LIBRARY_PATH environment variable. This is probably the simplest solution for you. You can always change this in a wrapper script for your executable.
Alternatively, just specify the minimum library version that your users need to have installed on the system.

A: The probably easiest way to create a Qt application package on Linux is probably linuxdeployqt. It collects all required files and lets you build an AppImage which runs on most Linux distributions.
Make sure you build the application on the oldest still-supported Ubuntu LTS release so your AppImage can be listed on AppImageHub.

A: You can look into QtCreator folder and use it as an example. It has qt.conf and qtcreator.sh files in QtCreator/bin.
lib/qtcreator is the folder with all needed Qt *.so libraries. Relative path is set inside qtcreator.sh, which should be renamed to you-app-name.sh
imports,plugins,qml are inside bin directory. Path to them is set in qt.conf file. This is needed for QML applications deployment.

A: This article has information on the topic. I will try it myself:
http://labs.trolltech.com/blogs/2009/06/02/deploying-a-browser-on-gnulinux/
In a few words:

*

*Configure Qt with -platform linux-lsb-g++

*Linking should be done
with –lsb-use-default-linker

*Package everything and deploy (will
need a few tweaks here but I haven't yet tried it sorry)


text:
Q: align: moving numbers in equations with bulky objects up automatically I apologize in advance if this is a duplicate, yet I was unable to find what I am looking for in the existing posts. align has the nice feature of moving the equation number down if there is no space in the current line, e.g.
\documentclass[fleqn]{article}
\usepackage{amsmath}
\usepackage{tikzducks}
\begin{document}
This is the standard output:
\begin{align}
 \vcenter{\hbox{\tikz[scale=2,remember picture]{%
 \duck[graduate=gray!20!black,tassel=red!70!black];
 \coordinate (B1) at (1,0.1);
 }}}~=~\int\!\mathrm{d}^4x\,
 \int\!\mathrm{d}^4y\,\int\!\mathrm{d}^4z\,
 \frac{1}{(x^2-m^2)\,(y^2-m^2)}
\end{align}
\tikz[overlay,remember picture]{\draw[gray](B1)--++(9.3cm,0);}
I want to move the equation number up, but not by hand:
\begin{align}
 \vcenter{\hbox{\tikz[scale=2,remember picture]{%
 \duck[graduate=gray!20!black,tassel=red!70!black];
 \coordinate (B2) at (1,0.1);
 }}}~=~\int\!\mathrm{d}^4x\,
 \int\!\mathrm{d}^4y\,\int\!\mathrm{d}^4z\,
 \frac{1}{(x^2-m^2)\,(y^2-m^2)}\notag\\[-0.6cm] % <-adjusted by hand
\end{align}
\tikz[overlay,remember picture]{\draw[gray](B2)--++(9.3cm,0);}
\end{document}

For those who do not like ducks, think of them as placeholders for, say, Feynman diagrams. (The gray lines are just to guide your eye.) As you can see, the equation number would not fit in the current line, and align moves it kindly into the next line. However, the first equation wastes some vertical space. I am of course able to fix this by hand, as illustrated in the second equation, or might also cook up a complicated macro for this. The question is whether there is a simple way to move the number up like in equation (2) without tuning things by hand.

A: There is \raisetag (to be used with care, because it moves up also the following text).
\documentclass[fleqn]{article}
\usepackage{amsmath}
\usepackage{tikzducks}

\begin{document}
This is the standard output:
\begin{equation}
\begin{gathered}
  \qquad % just to make it bigger and move down the number
  \begin{tikzpicture}[scale=2]
    \duck[graduate=gray!20!black,tassel=red!70!black];
    \coordinate (B1) at (1,0.1);
  \end{tikzpicture}
  \qquad % just to make it bigger and move down the number
\end{gathered}
=\int\! d^4x
 \int\! d^4y
 \int\! d^4z\,
 \frac{1}{(x^2-m^2)\,(y^2-m^2)}
\end{equation}
Some text following
some text following
some text following
some text following
some text following
\begin{equation}
\begin{gathered}
  \qquad % just to make it bigger and move down the number
  \begin{tikzpicture}[scale=2]
    \duck[graduate=gray!20!black,tassel=red!70!black];
    \coordinate (B1) at (1,0.1);
  \end{tikzpicture}
  \qquad % just to make it bigger and move down the number
\end{gathered}
=\int\! d^4x
 \int\! d^4y
 \int\! d^4z\,
 \frac{1}{(x^2-m^2)\,(y^2-m^2)}
\raisetag{\baselineskip}
\end{equation}
Some text following
some text following
some text following
some text following
some text following

\end{document}

Note gathered instead of the clumsy \vcenter{\hbox{...}}.

No ~=~, please, it's wrong. And, sorry, but I can't stand the upright "d".

A: Changing amsmath to do it will be more difficult and will break more things than just the line :P
Instead of manually adjusting the height, you can use a \strut. From the TeXbook:

Plain TeX defines \strut to be an invisible box of width zero that extends just enough above and below the baseline so that you would need no interline glue at all if every line contained a strut.

So this is exactly the amount you want to raise the equation number. You just have to replace the \\[-0.6cm] by \\[-\dimexpr2\ht\strutbox\relax] (The \strutbox is the box that is placed when you place the \strut). Notice that you need to return twice the height of the \strutbox to counteract the \\.

\documentclass[fleqn]{article}
\usepackage{amsmath}
\usepackage{tikzducks}
\begin{document}
\pagenumbering{gobble}
This is the standard output:
\begin{align}
 \vcenter{\hbox{\tikz[scale=2,remember picture]{%
 \duck[graduate=gray!20!black,tassel=red!70!black];
 \coordinate (B1) at (1,0.1);
 }}}~=~\int\!\mathrm{d}^4x\,
 \int\!\mathrm{d}^4y\,\int\!\mathrm{d}^4z\,
 \frac{1}{(x^2-m^2)\,(y^2-m^2)}
\end{align}
\tikz[overlay,remember picture]{\draw[gray](B1)--++(9.3cm,0);}
I want to move the equation number up, but not by hand:
\begin{align}
 \vcenter{\hbox{\tikz[scale=2,remember picture]{%
 \duck[graduate=gray!20!black,tassel=red!70!black];
 \coordinate (B2) at (1,0.1);
 }}}~=~\int\!\mathrm{d}^4x\,
 \int\!\mathrm{d}^4y\,\int\!\mathrm{d}^4z\,
 \frac{1}{(x^2-m^2)\,(y^2-m^2)}\notag\\[-\dimexpr2\ht\strutbox\relax] % <- not anymore!
\end{align}
\tikz[overlay,remember picture]{\draw[gray](B2)--++(9.3cm,0);}
\Large
The font size can even change!
\begin{align}
 \vcenter{\hbox{\tikz[scale=1.5,remember picture]{%
 \duck[graduate=gray!20!black,tassel=red!70!black];
 \coordinate (B3) at (1,0.1);
 }}}~=~\int\!\mathrm{d}^4x\,
 \int\!\mathrm{d}^4y\,\int\!\mathrm{d}^4z\,
 \frac{1}{(x^2-m^2)\,(y^2-m^2)}\notag\\[-\dimexpr2\ht\strutbox\relax] % <- not anymore!
\end{align}
\tikz[overlay,remember picture]{\draw[gray](B3)--++(9.3cm,0);}

\end{document}


text:
Q: Can not see data on VisualForce page for Big Objects data I created a Visual force page for Big object data to be seen. However when i import data from workbench i am unable to see the full data in VF page. For some reason i can only 2 records out of 10 and those 2 record are first and last record in the table. I can not figure out what is the problem that the full data wouldn't be visible in VF table. please advise me what can be the solution to this issue. i am very new to the salesforce and doesnt know much about VF and Apex codes.
Visualforce Codes:
<apex:page controller="EmailArchive" title="Email Archive">
<apex:sectionHeader title="EmailArchive" subtitle="All Archived Email"/>
<apex:pageBlock >
    <apex:pageBlockSection columns="1" >
        <apex:pageBlockTable value="{!listOfEmailArchive}" var="email">
        <apex:column value="{!email.ID__c}"/>
        <apex:column value="{!email.Parent_ID__c}"/>
        <apex:column value="{!email.Message_Date__c}"/>
        <apex:column value="{!email.Subject__c}"/>
        <apex:column value="{!email.Text_Body__c}"/>
        <apex:column value="{!email.HTML_Body__c}"/>
        <apex:column value="{!email.FROM_ADDRESS__c}"/>
        <apex:column value="{!email.TO_ADDRESS__c}"/>
       </apex:pageBlockTable>
    </apex:pageBlockSection>
</apex:pageBlock>

Apex class:
public class EmailArchive{
public List<Email_Archive__b> listOfEmailArchive {get;set;}
public EmailArchive(){
    listOfEmailArchive = [SELECT Subject__c, ID__c, CREATED_DATE__c, FROM_ADDRESS__c, Headers__c, TO_ADDRESS__C, Last_modified_DATE__c, System_MOD_Stamp__c, Text_Body__c, HTML_Body__c, From_Name__c, Validated_From_Address__c, CC_Address__c, BCC_Address__c, Incoming__c, Has_Attachment__c, Status__c, Message_Date__c, Is_Deleted__c, Is_Externally_Visible__c, Message_Identifier__c, Reply_to_Email_Message_ID__c, Thread_Identifier__c, Is_Cliet_Managed__c, Related_to_ID__c, Last_modified_by__c, Parent_ID__c, Created_by_ID__c FROM Email_Archive__b];
    if(listOfEmailArchive == null){
        listOfEmailArchive = new List<Email_Archive__b>();
    }
}

}
enter image description here

I have inserted all the screenshots that might be needed to find the problem.
Thank you

A: I don't have an authoritative answer here, but I have an idea as to what may be the issue.
BigObjects are intended to hold millions of records or more. The SOQL that is supported by BigObjects is intentionally very limited, and the design intent is that you should be writing a query against the fields you defined as part of the BigObject's index when you created it:

You can query the fields in a big object's index using a subset of standard SOQL commands.
Build an index query starting from the first field defined in the index, without gaps between the first and last field in the query. You can use =, <, >, <=, or >=, or IN on the last field in your query. Any prior fields in your query can only use the = operator. The !=, LIKE, NOT IN, EXCLUDES, and INCLUDES operators are not valid in any query.

While I can't locate a reference that states that BigObjects cannot be queried without a filter in regular SOQL (as opposed to Async SOQL), I'm speculating that this unusual behavior you've observed is a species of undefined behavior stemming from running an unfiltered SOQL query against a BigObject.
Since you certainly cannot expect such a query to work in production, when your BigObject's data is populated at scale, I would recommend rewriting the query against the BigObject's index fields to see whether the result is as expected in this situation.


text:
Q: How to make perl regex options conditional DON'T ASK WHY but...
I have a regex that needs to be case insensitive if run on windows BUT case sensitive when run on *nix.
Here is an example snippet of what I am kind-of doing at the moment.
sub relative_path
{
    my ($root, $path) = @_;

    if ($os eq "windows")
    {
        # case insensitive with regex option 'i'
        if ($path !~ /^\Q$root\E[\\\/](.*)$/i)
        {
            print "\tFAIL:$root not in $path\n";
        }
        else
        {
            return $1;
        }
    }
    else
    {
        # case sensitive
        if ($path !~ /^\Q$root\E[\\\/](.*)$/)
        {
            print "\tFAIL:$root not in $path\n";
        }
        else
        {
            return $1;
        }
    }
    return "";
}

Argh! The repetition hurts my OCD but my perl-fu is weak. Somehow I want to make the regex option 'i' for case-insensitive conditional but I don't now how?

A: You can use an extended construct to specify the option. For example:
#!/usr/bin/env perl

use warnings; use strict;

my $s = 'S';

print check($s, 'i'), "\n";
print check($s, '-i'), "\n";

sub check {
    my ($s, $opt) = @_;
    return "Matched" if $s =~ /(?$opt)^s\z/;
    return "Did not match";
}

See perldoc perlre.

A: You can create patterns and store them in scalars using the qr operator:
sub relative_path
{
    my ($root, $path) = @_;

    my $pattern = ($os eq "windows") ? qr/^\Q$root\E[\\\/](.*)$/i : qr/^\Q$root\E[\\\/](.*)$/;

    if ($path !~ $pattern)
    {
        print "\tFAIL:$root not in $path\n";
    }
    else
    {
        return $1;
    }
}

This might not be 100% perfect, but hopefully you should get the idea.
Make sure to check out the section "Quote and Quote-Like Operators" in perlop.

EDIT: Okay, here's a DRY solution since people are complaining about it.
sub relative_path
{
    my ($root, $path) = @_;

    my $base_pattern = qr/^\Q$root\E[\\\/](.*)$/;
    my $pattern = ($os eq "windows") ? qr/$base_pattern/i : $base_pattern;

    if ($path !~ $pattern)
    {
        print "\tFAIL:$root not in $path\n";
    }
    else
    {
        return $1;
    }
}

A: In addition to achieving the stated objective, this properly handles volumes unlike the regex patterns previously posted.
use Path::Class qw( dir );

sub relative_path {
   my ($root, $path) = @_;

   if ($^O =~ /Win32/) {
      require Win32;
      $root = Win32::GetLongPathName($root);
      $path = Win32::GetLongPathName($path);
   }

   $root = dir($root);
   $path = dir($path);

   if ($root->subsumes($path)) {
      return $path->relative($root);
   } else {
      print "\tFAIL:$root not in $path\n";
      return "";
   }
}

By the way, it's not very appropriate to handle the error there. The function should return an error signal (return undef, throw an exception, etc) and the caller should handle it as it sees fit. Separations of concerns.

A: You can also do it using local modifiers (perl extended regexes option):
sub relative_path
{
    my ($root, $path) = @_;

    my $pattern = "^\Q$root\E[\\\/](.*)$";
    $pattern = "(?i)$pattern" if ($os eq "windows");
    if ($path =~ /$pattern/)
    {
        return $1;
    }
    else
    {
        print "\tFAIL:$root not in $path\n";
    }
}

(after I typed my answer I saw that Sinan also suggested it, but I decided to post my answer as well, since it gives a concreter answer to the question)


text:
Q: Distance calculation between two points using esri javascript api We are building a web application that uses an esri map. What i am trying to do is calculate the distance between two points. The coordinates for these points are in two separate json objects.
Next i generate two esri points by parsing the latitude and the longitude values from these two json objects. Esri points require spatial reference, so i set the spatial reference of the mapView as the spatial reference for the two points.
The Problem: When i select the two points, it completely rewrites the latitude and the longitude of one of the points. This results in a ridiculous calculation of the two points.
This is what i have tried
//calling the distance function

distance = this.distanceCalculator(incidentCenter, residence);

//distance calc function
  private distanceCalculator(firstPt, secondPt): any {
    //this.measureLayer.removeAll();

    // When calculating the distance betweeen two points , we need to decypher the points coming in and attach a spatial reference.
    const pointA: esri.Point = new this.Point({
      spatialReference: this.mapView$.value.spatialReference,
      latitude: firstPt.latitude,
      longitude: firstPt.longitude
    });

    //so whats happening here is that
    const pointB: esri.Point = new this.Point({
      spatialReference: this.mapView$.value.spatialReference,
      latitude: secondPt.latitude,
      longitude: secondPt.longitude
    });

    console.log("Point a and B");
    console.log("point a: ", pointA);
    console.log("point b: ", pointB);

    // Next we call the GemoetryEngine distance function and calculate the distance between the two points.

    try {
      const miles = this.GeometryEngine.distance(pointA, pointB, 'kilometers');
      const kms = miles * this.MilesToKm;
      return kms.toFixed(2);
    } catch (e) {
      this.logger.error('Error indistanceCalculator ', e);
    }
  }

Screenshots
After selecting the two points , i noticed that the second point has incorrect lat/long values.

This calculates the distance between the two points as

the actual distance is supposed to be the following (esri widget result)

If i were to select the two points again, it generates the correct distance

A: Egg on face moment for me, I was setting the lat and long wrong one point in the code that resulted in this error. Thank you all for the help.


text:
Q: Rails, passenger, communicating between threads I want to write in simple logger for my  that puts messages in memory and, in background, every X seconds write it to a database.
Here is the buffered logger code:
module BufferedLogger
  def buffer
    @buffer ||= []
  end

  def log( message )
    buffer << message
  end

  def write_buffer
    while message = buffer.shift do
      # save the message in nosql
    end
  end

  def repeat_every( interval )
    Thread.new do
      loop do
        start_time = Time.now
        yield
        elapsed = Time.now - start_time
        sleep([interval - elapsed, 0].max)
      end
    end
  end

  extend self

  thread = repeat_every(10) do
    write_buffer
  end

end

In development, this works fine, buffer() access to the same @buffer var in both log and write_buffer method. But as soon as I go to production or staging env, i.e. as soon as I'm behind passenger, this @buffer don't seem to be shared anymore.
Any pointer?

A: Since passenger create separate process, and how these process will persists depends on passenger's algorithm, I guess it will not work well as you expect. (btw, I had bad experience in this regard using global variables/class variables.)
My suggestion to buffer the log is, use logger like fluentd as intermediate processor. Fluentd can monitor and gather the log. You can write a plugin to write the collected log to DB. I think this will suit your needs.

A: If you're trying to save database I/O it's usually not an issue, so you might be prematurely optimizing.
If I needed to buffer database writes, I'd probably turn off autocommit, then write the records as they occur, with a commit after n records, or after n seconds, whichever comes first.
Databases can handle a lot of traffic and have all sorts of internal buffering also, so your disk and system impact is minimized. If your database is on the same machine as your Rails host, then you should split them for performance reasons.
Otherwise, unless you have gathered metrics and can point to database I/O as a problem,  I'd say write the code and don't worry about buffering until that problem surfaces.