text:
Q: switching from implementation to ADTS Hi im new to ADTS and im trying to convert this file from a implemented version to just using the collection as practice
   import java.util.HashMap;
   public class HashConvert
   {
    public static void main(String args[])
    {

        HashMap <String, Object> capCity = new HashMap<String, Object>(20);

        String[] data = {"Darwin", "Sydney", "Melbourne", "Brisbane", "Canberra", "Hobart",   "Perth"};

        for (int i=0; i < data.length; i++)
        {

            capCity.tab(data[i], "O"+data[i]);
        }

Im trying to edit it to use all HashMaps methods from the collections,
I have already written a class that is implemented similar to a "hashMap" but i dont want to use it any more, want to use the ADT's methods
The "tab" function does not seem to be working and comes up with the identifier required.
i tried doing an override method but it doesn't work
thank you


text:
Q: How to take into account the minimum value vertex in Dijsktra algorithm? I have read this post Understanding Time complexity calculation for Dijkstra Algorithm to understand the complexity of Dijkstra algorithm. However, I can't see where the time to pick at each iteration the minimum value vertex (the one whose value will be fixed after this iteration) inside the heap is involved in the calculus... Could someone clearly explain me where it is involved ?
Thanks !

A: Dijkstra algorithm is something like this
repeat V times:
    take min from heap; // Works in O(1)
    erase min from heap; // Works in O(log V)
    for vertices connected with current:
        update distance; // Works in O(1)
        update value in heap; // Works in O(log V)

The first cycle makes V iterations and the second makes sum of degrees of all vertices iterations, so it's 2 * E or O(E) iterations. Total complexity is O(VlogV + ElogV)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firebase Realtime Database calls marked as cancelled for react app Currently using Firebase's Realtime Database with my react app. When writing with the following:
const db = realtimeDatabase.getDatabase(app);
realtimeDatabase.set(realtimeDatabase.ref(db, 'test/' + entry), {
    test: "test",
});

It does not throw an error or write to the database. When checking the network tab in developer tools, the requests that start with

.lp

Appear as red with no status code and are denoted as cancelled.


text:
Q: Eclipse JDT: how to get data model for Java content assist When writing Java code on Eclipse IDE, press Control + Space will pop up the content assist window.
For example, the content assist window for System. will list all the available fields and methods for class System.
I need to access the "data model" for the content assist window by code.
Using the above example, it is: given the class name System, how can I retrieve all the available fields and methods?
I spent some time on the source code of these three classes on grepcode.com:
org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext
org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposalComputer
org.eclipse.jdt.ui.text.java.CompletionProposalCollector

It looks like the an ICompilationUnit instance is used to provide the fields and method names.
Then I don't understand how to generate the ICompilationUnit instance for a class in jre system library or third party library? Or if I didn't read the code in a correct way, then how did the program find fields and methods name? (I don't need to worry about the offset and UI stuff, just the "data model" part).

A: It seems that the only option is to create a (temporary) compilation unit, which in turn requires a properly set up Java project. The infrastructure is necessary for JDT to know which JRE is used, which compiler settings are used, etc.
See here how to set up a Java project, and here how to get a compilation unit.
The compilation unit would look something like
class Foo {
  void bar() {
    java.lang.System.
  }
}

and codeComplete() would have to be called with an offset that denotes the position right after System..

A: You can use the Eclipse JDT Language Server, which is used by different editors already (e.g. Visual Studio Code, and EMACS):
https://github.com/eclipse/eclipse.jdt.ls
This way, you'll be able to provide many JDT features available in the LSP definition (e.g. code completions, references, diagnostics, etc.):
https://microsoft.github.io/language-server-protocol/specifications/specification-current/
There are bindings for Java available with LSP4J over Maven:
<dependency>
    <groupId>org.eclipse.lsp4j</groupId>
    <artifactId>org.eclipse.lsp4j</artifactId>
    <version>0.12.0</version>
</dependency>

A simple implementation might look like this:
ExpressionLanguageClient.java
import org.eclipse.lsp4j.MessageActionItem;
import org.eclipse.lsp4j.MessageParams;
import org.eclipse.lsp4j.PublishDiagnosticsParams;
import org.eclipse.lsp4j.ShowMessageRequestParams;
import org.eclipse.lsp4j.jsonrpc.services.JsonNotification;
import org.eclipse.lsp4j.services.LanguageClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;

public class ExpressionLanguageClient implements LanguageClient {

    private final static Logger logger = LoggerFactory.getLogger(ExpressionLanguageClient.class);

    final private ExpressionCodeAssistantService expressionCodeAssistantService;

    public ExpressionLanguageClient(ExpressionCodeAssistantService expressionCodeAssistantService) {
        this.expressionCodeAssistantService = expressionCodeAssistantService;
    }

    @Override
    public void telemetryEvent(Object o) {
        // TODO
        logger.info("Expression LSP telemetry: " + o);
    }

    @Override
    public void publishDiagnostics(PublishDiagnosticsParams publishDiagnosticsParams) {
        // TODO
        logger.info("Expression LSP diagnostics: " + publishDiagnosticsParams);
    }

    @Override
    public void showMessage(MessageParams messageParams) {
        // TODO
        logger.info("Expression LSP show message: " + messageParams);
    }

    @Override
    public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams showMessageRequestParams) {
        return null;
    }

    @Override
    public void logMessage(MessageParams messageParams) {
        expressionCodeAssistantService.lspLogMessage(messageParams.getMessage());
    }

    @JsonNotification("language/status")
    public void languageStatus(Object o) {
        // avoid unsupported notification warnings
    }
}

CodeAssistantService.java
// start the Eclipse JDT LS required for the code assistant features
try {
    String[] command = new String[]{
            "java",
            "-Declipse.application=org.eclipse.jdt.ls.core.id1",
            "-Dosgi.bundles.defaultStartLevel=4",
            "-Declipse.product=org.eclipse.jdt.ls.core.product",
            "-Dlog.level=ALL",
            "-noverify",
            "-Xmx1G",
            "-jar",
            ".../eclipse.jdt.ls/org.eclipse.jdt.ls.product/target/repository/plugins/org.eclipse.equinox.launcher_1.6.400.v20210924-0641.jar",
            "-configuration",
            ".../eclipse.jdt.ls/org.eclipse.jdt.ls.product/target/repository/config_linux",
            "-data",
            "...",
            "--add-modules=ALL-SYSTEM",
            "--add-opens java.base/java.util=ALL-UNNAMED",
            "--add-opens java.base/java.lang=ALL-UNNAMED"
    };

    Process process = new ProcessBuilder(command)
            .redirectErrorStream(true)
            .start();

    ExpressionLanguageClient expressionLanguageClient = new ExpressionLanguageClient(this);

    launcher = LSPLauncher.createClientLauncher(
            expressionLanguageClient,
            process.getInputStream(),
            process.getOutputStream()
    );
    launcher.startListening();
} catch (Exception e) {
    logger.error("Could not start the language server", e);
}

Be sure to customize the commands where necessary (paths and config_mac/linux/windows).
As soon as the language server is running (maybe listen for a log message), you need to call the init event (be sure to call from a separate thread, if you call it from the language client, because it would cause a deadlock otherwise):
InitializeParams initializeParams = new InitializeParams();
initializeParams.setProcessId(((int) ProcessHandle.current().pid()));

// workspace folders are read from the initialization options, not from the param
List<String> workspaceFolders = new ArrayList<>();
workspaceFolders.add("file:" + getTempDirectory());

Map<String, Object> initializationOptions = new HashMap<>();
initializationOptions.put("workspaceFolders", workspaceFolders);
initializeParams.setInitializationOptions(initializationOptions);

CompletableFuture<InitializeResult> init = launcher.getRemoteProxy().initialize(initializeParams);
try {
    init.get();
    logger.info("LSP initialized");
} catch (Exception e) {
    logger.error("Could not initialize LSP server", e);
}

Now, you're able to get code completions like this:
TextDocumentItem textDocumentItem = new TextDocumentItem();
textDocumentItem.setText(isolatedCodeResult.getCode());
textDocumentItem.setUri("file:" + dummyFilePath);
textDocumentItem.setLanguageId("java");

DidOpenTextDocumentParams didOpenTextDocumentParams = new DidOpenTextDocumentParams();
didOpenTextDocumentParams.setTextDocument(textDocumentItem);
launcher.getRemoteProxy().getTextDocumentService().didOpen(didOpenTextDocumentParams);

TextDocumentIdentifier textDocumentIdentifier = new TextDocumentIdentifier();
textDocumentIdentifier.setUri("file:" + dummyFilePath);

CompletionParams completionParams = new CompletionParams();
completionParams.setPosition(new Position(line + lineOffset, column));
completionParams.setTextDocument(textDocumentIdentifier);

CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion =
        launcher.getRemoteProxy().getTextDocumentService().completion(completionParams);

logger.info("Found completions: " + completion.get().getRight().getItems());

Make sure, the dummyFilePath is a an existing java file. The content does not matter, but it needs to exist in order for the JDT LS to work.
I am not sure, whether it would be better to always sync the source files with the language server. Maybe this would be faster, especially for large projects. If you just need content assistant features for minor source files, the provided example should be sufficient.

A: You could try to use the java reflection API to get all the members of this certain class (YourClass.getMethods() or YourClass.getDeclaredMethods()).
To make it dynamic according to your input you can use Class.forName(<fullClassName>) to get the respective class (see this post for further information about that).
The problem you might run into is that you have to give the full qualified class name therefore you might have to check the imports to find out in which package you have to search for the respective class but it's the only way to go with this method.
Simple names are just not always unique and therefore not suitable for this kind of search (explained here.


text:
Q: signup with google or facebook I am new in laravel and I want to login with google and facebook but I have no idea how to use and integrate in laravel 5.6  Please suggest and help for how to sign up with google and facebook.

A: There's a package called socialite that makes integrating with social services alot easier. You can check the documentation at Laravel Socialite.
You pull in the socialite package via composer, and then put the different required social site keys and secrets in the config/services.php file as required.


text:
Q: How to organize integration tests using maven? There are two separated projects: client and server. How can I test client-server interaction properly? Is there a simple solution to do it using maven?
This is how I do:
1) I've got a junit test that runs client and server in different threads. I use @BeforeClass to start client/server and @AfterClass to stop.
2) I run all the tests including unit tests using mvn test
Is it ok to run client and server in one process? Do I have to divide unit and integration tests?


text:
Q: ADS1115 measuring body resistance has a noisy output, how to fix it? I am trying to measure body resistance with an ESP8266 and ADS1115 without much success.
At first the ADS1115 power supply was connected to 3.3V but there was a lot of noise. I then powered it from a battery but the noise wasn't get reduced, maybe because it needs to share ground with the Arduino for I2C.
The ADS1115 ADC pin is connected to a voltage divider of body probes and 500k to ground.
I cannot power the Arduino from a battery as I need to monitor results fast enough through serial monitor, specifically a plotter to see the results. The moment I touch (only) the ADC pin, the noise intensifies as if I am an antenna but if I touch the positive probe which is same as the ADS1115 powersupply, the noise gets reduced to nothing.
I also tried changing sample rate, 860sps is good, 8sps better and 128sps (default) is worst.
Is there anything I can do get rid of the noise? My main purpose is to make a somewhat accurate acupressure point locator.  I doubt if I am heading the right direction but still would like see some noise free curves.
Wiring & Schematics:

8 SPS plotter:

128 SPS plotter:

Update: Probing body after attaching 100nf ceramic capacitor on probes (8SPS):

A: Question
How come human body impedance measurement using ADC such as ADS1115 is so noisy?

Answer

*

*Well, it is your body that is noisy, not ADS1115.

*This is a hundred year old problem.  The solution is the Einthoven Triangle.  See Ref 1 below for more details.

*The Einthoven Triangle is a very specific case of eliminating noise by using the concept of "differential signalling". The OP needs to wiki to know more about differential input and differential amplifier.

*For ADS1115, there are four single ended inputs or two differential inputs, which should always be used to reduce noise.

*Differential signalling can reduce noise, but never eliminate it.  So we need to use other tricks, including using analog/digital filtering, which is actually already implemented in 16-bit and 24-bit ADCs such as ADS1115, HX711 and NAU7801.

*Another simple trick to eliminate noise is to use moving time average, to "average out" too noisy readings/measurements, or exclude the measurements to far away from the moving average (actually sort of very simple digital filtering).

*ADS1115 can either do continuous (up to about 800 conversions per second) or single shot mode, and its PGA (Programming Gain Amplifier) can entertain a wide input range of about ±250mV to about ±6V.  This programming gain setting is very important to fit the body impedance situation which might be of order of uA or mA, Note 1.
Note 1: ADS111x ΔΣ ADCs are based on the principle of oversampling, ... to reduce noise of low level signals, see Section 8.1 of Datasheet, and also Technical Documentation.

*The OP's interest to locate acupressure points.  So first thing first is to specify the acupressure points and do some rough voltage/current measurements using perhaps a cheapy oscilloscope.
/ to continue, ...

References
(1) ECG monitoring using ADS8232 and MCP3008 noise problem - asked 2019may13, viewed 5k times
(2) Raspberry pi interfacing with AD8232 using python - 2021mar01, viewed 305 times
(3) ADS1115 Ultra-Small, Low-Power, I2C-Compatible, 860-SPS, 16-Bit ADCs With Internal Reference, Oscillator, and Programmable Comparator - TI
(4) ADS1115 16-bit, 860-SPS, 4-channel, delta-sigma ADC with PGA, oscillator, VREF, comparator and I2C Technical Documentation
(5) Acupressure Points for Back Pain - AcupressurePoints.Net
(6) Valley Closing Point (合谷穴) - Wikipedia
https://zh.wikipedia.org/wiki/%E5%90%88%E8%B0%B7%E7%A9%B4
(7) ADS1115 Inconsistent conversion results and full scale setting problem
(8) Bio-impedance circuit inputs - EESE 2021may31
(9) A Comprehensive Study of the Howland Current Pump AN-1515 - TI 2008jan
(10) Medical Disposable Electrode Patch ECG Accessories Non-woven ECG Electrode Pads - US$9.5  50pcs/pack
(11) ECG/EMG/EKG 3-Lead Sensor Cable-Electrode Pads Muscle Sensor Accessories Plug - AliExpress US$6

Appendices
Appendix A - The Einthoven Triangle

Appendix B - ADS1115 Block Diagram

Appendix C - ECG Measurement Noisy Example
(1) ECG monitoring using ADS8232 and MCP3008 noise problem - asked 2019may13, viewed 5k times

Appendix D - Acupressure Points for Back Pain
(5) Acupressure Points for Back Pain - AcupressurePoints.Net

When one uses acupressure or acupuncture endorphins and serotonin is released in the body and acts as a natural painkiller.
By applying pressure between the thumb and forefinger also known as LI-4 is effective to not only relieve back pain but other ailments as well.
Here one can apply pressure while relaxing on a bed or sofa on this Acupoint for at least 10 seconds and release for 5 seconds – repeat this method at least three times.

Appendix D - External/mains noise measurement and ADS1115 small signal full range setting calibration

*

*Now before measuring body resistance using ADS1115, I think we need to measure the magnitude of the external/mains noise.  We need to make sure the external/mains noise is small enough not to affect the body resistance related signals.

*I used my Rigol DS1054Z 50MHz scope to measure the noise level of the following signal sources: (a) 10kΩ, 10MΩ, 10cm wire, 30cm wire. I found the noise is in a range of 10mVpp to 100mVpp.  So it should not be meaningless if we set the ADS1115 full range to the smallest +/-250mV

*So we now need to check three things: (a) The magnitude of the body resistance/voltage, (b) appropriate gain factor setting of the ADS1115 PGA (Programmable Gain Amplifier), (c) If ADS1115 does indeed filter out the external/mains noise.

A: *

*You're lucky: body impedance measurements are a simpler problem than measuring external voltages in presence of noise. As long as you can keep the electrode-to-skin resistance relatively constant by strain-relieving the leads so they don't tug on the electrodes, it's not hard to get good signals.

*The core idea is to drive a small AC current through the body, and synchronously demodulate the resulting small AC voltage. The synchronous demodulation acts as a narrowband filter that will not be sensitive to ECG, EMG, 50/60Hz interference, nor similar artifacts. The skin impedance drops significantly with frequency, so you'll want to measure at 10-20kHz where it's hundreds of times lower than around DC (!).

*In your case, you'd be driving a preset amplitude square wave current from a current source, with zero mean value (that's super important!) - IIRC clinical equipment uses on the order of 1uA amplitude. Take an ADC sample each time the current is reversed. Compute the voltage drop by adding up a number of ADC samples, alternating their signs, i.e. sample1 - sample2 + sample3 - sample4 and so on - you'd want to average across multiple samples, for respiration a 100ms worth of samples is a good starting point. The impedance is then the measured voltage divided by the driving amplitude. Since the drive amplitude should be fixed, the division is just multiplying by the reciprocal.

*Since your ADC is not fast enough, you can instead use a digital switch to invert the polarity of the signal coming out of the preamplifier, synchronously with the switching of the polarity of the drive current. The slow ADC will then naturally act as an averager.

*If you're feeling fancy and have some computing cycles to burn, the AC signal can come from a DAC, and be a band-limited random signal (i.e. pass output from rand() though a FIR or IIR filter than shapes the bandwidth appropriately) - say between 10kHz and 50kHz. The voltage is then cross-correlation of the signal sent to the DAC with the signal received from the ADC - this is much less sensitive to narrowband interference (also called CW signals). On the other hand, the human body has a complex impedance that is frequency-dependent, so this approach only works up to a point - beyond that, you'll need to compute complex impedance as a function of frequency, and that will come from convolution of the DAC and ADC signals.

*As a point of reference, the respiration signal (if that's what you're after) is about 1 Ohm in amplitude, and IIRC the EKG Lead II is most sensitive i.e. will yield highest impedance amplitude.


text:
Q: Laravel redirect to root on request validation error I have a required field in a Laravel Request Class and when that field is not present in the request,
the request is redirected to root '/'.
I am sending the request via Postman.

A: If laravel validator finds errors in the request it will redirect you back to the previous page with errors. If the request is AJAX however, it will return you a simple JSON response with a 422 status code.


text:
Q: how we can include "HttpParam " in android studio version 6.0 i am using android studio 1.5.1 API 23, when we use "HttpParams" in a java programme we got some error like  we can not use it in this version so how i can include it in my android studio ?
    @Override
    protected Void doInBackground(Void... params) {
        ArrayList<NameValuePair> dataToSend = new ArrayList<>();
        dataToSend.add(new BasicNameValuePair("username", user.username));
        dataToSend.add(new BasicNameValuePair("name", user.name));
        dataToSend.add(new BasicNameValuePair("contect", user.contect));
        dataToSend.add(new BasicNameValuePair("BloodGroup", user.bloodgroup));
        dataToSend.add(new BasicNameValuePair("password", user.password));

        /*URL url = new URL(SERVER_ADDRESS +"Register.php");
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(link));*/
        //HttpParams httpParams = new BasicHttpParams();
        HttpParams httpRequestParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);

        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost(SERVER_ADDRESS +"Register.php");

       try{
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
           client.execute(post);
        }catch (Exception e){
            e.printStackTrace();

        }

        return null;
    }

A: API level 23 removed support for the Apache HTTP client.
If you really need to use the Apache HTTP classes, you can do so by including this in your build.gradle:
android {
    useLibrary 'org.apache.http.legacy'
}

However, you should do so only as a last resort. Instead you should look into options for migrating off of the Apache HTTP client.


text:
Q: How to correctly trim user input in React Native? I have TextInput that receives onChangeText as a prop:
<TextInput
  ...
  value={this.state.myString}
  onChangeText={this.updateInput.bind(this)}
/>

And updateInput is represented as:
updateInput(newString) {
  this.setState({ myString: newString.trim() });
}

This works for Android only. Is there some way to trim user input on both platforms (iOS, Android)?
Update
Actually, string is processed as trimmed, but you can still type as many whitespaces as you want on iOS. And if you type two whitespaces in a row the dot appears like it would be the end of the sentence. This is undesirable behaviour, is there a way to avoid it?
Link with example video: https://streamable.com/dzl3c

A: One way to trim like this with onChangeText property with value.trim(). Here is a working example on my RN 0.62.*
 <TextInput
      name="email"
      type="text"
      keyboardType="email-address"
      keyboardAppearance="light"
      returnKeyType="next"
      onChangeText={value => { setValue('email', value.trim(), true) }}
      blurOnSubmit={false}
      onSubmitEditing={() => this.password.focus()}
      autoCapitalize="none"
      autoCorrect={true}
      textContentType="emailAddress"
      editable={!isLoading}
      placeholder={Strings.INPUT_EMAIL_ADDRESS}
      placeholderTextColor={Theme.GRAY_LIGHT_COLOR}
      color={Theme.GRAY_DARK_COLOR}
      style={[styles.input, { borderColor: errors.email ? Theme.ORANGE_COLOR : Theme.PRIMARY_DARK_COLOR }]}
      ref={ref => this.email = ref} />

A: When you are submitting form add trim() to that value.


text:
Q: Benefits on splitting data in MySQL tables I have worked in a project that had a table somewhat like this:
tbl_texts
id, item_id, item, type, lang, value
1, 44, 'product', 'name', 'en', 'Product Name'
2, 44, 'product', 'description', 'en', 'Product description'
3, 55, 'category', 'name', 'en', 'Category name'
4, 55, 'category', 'name', 'fi', 'Category finnish name'

Out of the 6 fields, 1 was primary key and 4 was a combined index. Data was never selected with the primary key. Item_id, item, type, lang index was always used.
1) I was wondering if this is a good or a bad way to store data?
2) Is it bad design to have a table that you have to join twice (incase you want the name and description of a product).
3) Should I separate the data to tables like these:
tbl_product_texts
id, product_id, type, lang, value

tbl_category_texts

(etc.)

4) Or like this:
tbl_product_names
id, product_id, lang, name

tbl_product_descriptions
id, product_id, lang, description

(etc.)

5) Or even like this:
tbl_product_names_en
id, product_id, name

tbl_product_descriptions_en
id, product_id, description

(etc.)

I'm really confused which is the most optimal way to do this.

A: The 'best' way of storing data is a very open ended question. When designing a schema for data storage you need to take into account multiple aspects:

*

*How is your data accessed? (query optimisation)

*How is your data created?

*How likely is your database schema going to change in the future?

Wikipedia has a good article on data normalization here: http://en.wikipedia.org/wiki/Database_normalization
Personally I would create tables that make sense based on the underlying data. If products are sufficiently distinct to categories then I would store them in differing tables. While you have only provided a small sample of data, I am going to make the assumption that each product would have multiple names and description, but only one entry for each language. With that you would have the following:
Products:
  PK: id
  ...other columns that each product only has a single value for (price for example)

Product_Texts:
  PK,FK: product_id
  PK:    language
         name
         description

(PK - Primary Key, FK - Foreign Key)
If you then have queries that search for Names or Descriptions, you can then consider adding further keys on those fields as required.

A: Whether or not this is a bad implementation depends on what you want to do with it. This looks like it was designed for a variable combination of items, types and languages. The only one that stands out is the item column, which might not be needed since you already have the item_id.
If the current implementation works and it has no performance issues, there is probably no need to change anything. After all, improving the current situation will take time that might be better spend fixing important issues or building new features.
If this setup causes problems, you'll have to look into your requirements. For example, if you know there are a fixed amount of possible types that are always present for every item, this could be a solution (example only two possible types):
tbl_texts
id, item_id, item, lang, name_value, desc_value
1, 44, 'product', 'en', 'Product Name', 'Product description'
3, 55, 'category', 'en', 'Category name', 'Category description'
4, 55, 'category', 'fi', 'Category finnish name', 'Category finnish description'

You will have halved the amount of records and you have removed one search criterium, offsetting the extra columns that were added. Multiple optional types will likely make this solution a lot worse, an unknown amount of types will make it impossible.


text:
Q: How do I insert a document along with the result of a find query together in a collection in a single query in MongoDB? Suppose I have a collection named oldCollection which has a record like
{
name: "XYZ"
}

Now I want to insert this data into a new collection named newCollection. But I also want to add another key-value field (suppose a boolean field exists) for this same record like :
{
name: XYZ
exists:true
}

I am using find query to extract the required data and insert it into the new collection but how can I add more fields (like exists in the above example) in the same record?

A: Use $out aggregation stage:
db.collection.aggregate([
{
  "$addFields": { "exists": true }
},
{
  "$out": "resultedCollection"
}
])

see playground


text:
Q: How to prevent to tshark to create temp files under /tmp? I want to run followed command:
tshark  -l >  some.txt

As you see I write stdout to some.txt file.
But I get under /tmp folder temp files named etherXXXX* and these files can increase to  1-2G during 1 hour.
From tshark man I found to use -b option.
So I wrote:
tshark -b filesize:1024 -b files:5  -l >  some.txt

and got error: tshark: Maximum capture file size specified, but capture isn't being saved to a file.
From tshark.c code i found to use -w flag
tshark -b filesize:1024 -b files:5  -l -w >  some.txt

Now no files have been created under /tmp but some.txt file now bin file and i cant open it. Because -w flag make it like with cap extension. :(
How can I handle temp files?
BTW, some.txt file content was:
  0.118166 1.1.1.1 -> 2.2.2.2  HTTP GET /services/client/client.php?cnc=13 HTTP/1.1
  0.136235 1.1.1.1 -> 2.2.2.2  HTTP GET /services/client/clsWebClient.php HTTP/1.1
  0.271442 1.1.1.1 -> 2.2.2.2  HTTP GET /services/client/client.php?cnc=13 HTTP/1.1
  1.190018 1.1.1.1 -> 2.2.2.2  HTTP GET /services/client/clsWebClient.php HTTP/1.1

Thank you,

A: just use the -w <outfile> option to redirect touput to a file
in this case (without output redirection):
tshark -b filesize:1024 -b files:5  -l -w some.txt

The created file(s) will contain the binary data from the dump. You can later analyze this using -r <infile> to read the file and produce text output.


text:
Q: How to search on Text with Standard Analyser in Elastic Search I have a key value pair indexed as text in ES Mapping.
{key:myKey, value:MY_VALUE}

Whatever I do, let it be term, match, terms it doesn't hit in ES when I try to query for value
So: MY_VALUE will convert to terms of [my, value]

A: If you use a match query without any modification then it uses the same analyzer which was used to index the field, ie generates the same types of token for your search term and should produce you the search result.
As per Elasticsearch Match query Doc:

The provided text is analyzed before matching.
The match query is the standard query for performing a full-text
  search

As you have not provided any sample, let me show it using my sample data:
Index def
{
  "mappings" :{
    "properties" :{
        "title" :{
            "type" : "text" --> default standard analyzer would be used.
        }
    }
  }
}

Index sample docs
{
    "title": "foo bar"
}

{
    "title": "hello world"
}

search for foo
{
    "query" :{
        "match" :{
            "title" :"foo"
        }
    }
}

Result
 "hits": [
            {
                "_index": "standard",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.4700036,
                "_source": {
                    "title": "foo bar"
                }
            }
        ]

Search for foo bar
{
    "query" :{
        "match" :{
            "title" :"foo bar"
        }
    }
}

Result
"hits": [
            {
                "_index": "standard",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.9400072,
                "_source": {
                    "title": "foo bar"
                }
            }
        ]

Note: Searching for foo and foo bar both matches as standard token split the tokens on whitespace and you can use analyze API to check that as shown below:
{
  "text" : "foo bar",
  "analyzer" : "standard"
}

{
    "tokens": [
        {
            "token": "foo",
            "start_offset": 0,
            "end_offset": 3,
            "type": "<ALPHANUM>",
            "position": 0
        },
        {
            "token": "bar",
            "start_offset": 4,
            "end_offset": 7,
            "type": "<ALPHANUM>",
            "position": 1
        }
    ]
}

Edit: Based on the comment from OP(@AKASH GUPTA)
Now Elastic provides a default keyword field for text field but that's only for dynamic mapping and not for the static mapping and that too in the latest versions. Please refer this blog post and if you are using static mapping you can define your own corresponding keyword field.

A: Moving comment to answer: "It seems Elastic Search by default provides keyword for text fields. In this case it can be used as "title.keyword".
Refer: https://www.elastic.co/blog/strings-are-dead-long-live-strings
(Section: New Defaults.)
If you are having issues with "analyzed" text, and want a non analyzed string, you can append ".keyword" to your key.
before that do check if the mapping is present similar to:
"yourKey": {
     "type": "text",
     "fields": {
           "keyword": {
                "type": "keyword",
                "ignore_above": 256
           }
      }
}

If its not present, update the mapping similar as above.


text:
Q: Difference between "does" and "has had"

*

*Since when does he not have a pen?

*Since when has he not had a pen?

What is the difference between them?

A: Short answer:
Sentence 1. shows surprise and possibly anger, annoyance or doubt about him not having a pen.
Sentence 2. is ambiguous. It could mean exactly the same as sentence 1., or it could be a question about when he stopped having a pen.
Longer explanation
Let's start with the two meanings of "since when".
First meaning:
The two words can be used to ask about when something started:

Since when have the Winter Olympics been held? (since 1924)
Since when have you been unemployed? (since March 2020)

Second meaning
Merriam-Webster describes it like this:

since when idiom
--used to show that one is surprised and often angry, annoyed, or doubtful about what someone has said or done

"I'm a vegetarian." "Since when?"
"You told me to do it." "Since when did you start listening to me?"
Since when is it okay to cheat?

Note that this second meaning looks and sounds like a question, but is used rhetorically, and is not a request for an answer. Answering the question shows you don't understand the idiom, or you're purposefully ignoring the intended meaning. This second meaning is also somewhat rude and argumentative.
When using the first meaning --simply asking about when something started-- we must use a perfect tense with it, as in my two examples.
And if we want to use the second meaning --showing surprise and anger, annoyance or doubt-- then we often don't use a perfect tense, as in the Merriam-Webster examples. But it is possible to have the second meaning with a perfect tense:

Since when has anyone cared about what you had for breakfast?

A: Since when does he not have a pen? Let's make that declarative:
He doesn't have a pen since yesterday.
That is not standard English. It is colloquial.
Think of this:
He doesn't play tennis since yesterday.
In this case, you can see it is not standard.
The present simple is for repeated action or a general statement. Not for when something started in the past.
The present perfect is standard English here:
Since when has he not had a pen?
He hasn't had a pen [from the past until now, the time of speaking] since last week. [or more frequently: hasn't he  had] Or: Since when?

*

*Since yesterday.

Without intonation from a voice, attitude cannot be determined.
That said, they mean exactly the same thing but the simple present form would not be acceptable on an English exam.
Also, contracted forms are more frequent in spoken English and the standard English usage with since is the present perfect.
There is a sarcastic use of since when, yes. But your examples don't make it possible to declare that one is sarcastic and the other isn't.

A: Whilst they both mean the same when taken literally they have different meanings when used idiomatically in BrE.
"Since when does he not have a pen?" Is often used as an expression of annoyance, "he" is expected to carry or have been issued with a pen and have it available for use. It's similar to asking "Why doesn't he have a pen?"
"Since when has he not had a pen?"  can be used in a similar way, but it can also mean "For how long has he not had a pen? [What happened to it?]"

A: They both mean the same thing. However, expect to hear "Since when does he not have a pen" more often.


text:
Q: DataPortal.Fetch failed (Could not compile the mapping document: (unknown)) I added a new field in SQL server database. and implement all related properties in the application which is developed in NHibernate.
   [Property(Name = "IntervalUnit", Column = "IntervalUnit", NotNull = false)]
    private long _IntervalUnit = 0;

I don't have any hbm or XML file for properties.
but still I am getting this issue
DataPortal.Fetch failed (Could not compile the mapping document: (unknown))
What do I need to do?


text:
Q: Using a zero-sized array in Visual Studio 2013 C++ Working on a rather large project which for reasons that are out of my control require that a zero-length array is used as a pseudo-pointer.
The array in question is defined in of the .hpp files in one of the structs:
    struct mail_t {
        custom_enum_t  src;
        custom_enum_t  dest;
        uint16_t  length;
        uint8_t  data[ ];
    };

The error is thrown where data[ ] is defined (substituting data[0] has no effect).
The project can compile on Ubuntu with gcc 7.1.0 no problem.
Any ideas for a fix to compile this project with Visual Studio? I'm open to suppressing compiler warning, importing other libraries etc.

A: Since C++ doesn't support flexible array members, probably your best bet would be to use a "struct hack", the questionably legal feature that flexible array members were designed to replace.
Flexible array members were introduced in C99. Note that in your example, data is not a pointer. It's an array object whose effective size depends on the amount of memory allocated for the containing structure.
Using the struct hack, you could define the member as
uint8_t data[1];

That should get you past the compilation error. If you allocate extra memory for a struct mail_t object, you might be able to treat data as an array with a length greater than 1. But strictly speaking, accessing any element of data past element 0 has undefined behavior, and a compiler is free to take advantage of that fact for optimization purposes. (Since there's so much old code that uses the struct hack, C compilers typically avoid breaking it. I'm not sure whether that's also true of C++ compilers.)
An alternative might be to define data with a length at least as large as the number of elements you're going to access, and then allocate fewer that sizeof (struct mail_t) bytes to hold a structure. That might also run into undefined behavior, but my guess is that it's a bit more likely to "work".
(The right solution, of course, is to use a different data structure, perhaps a pointer pointing to a separately allocated array, or one of C++'s many container classes.)
The struct hack is discussed in question 2.6 of the comp.lang.c FAQ.


text:
Q: PHP Parse SOAP XML Response I can't figure out how to parse this XML response though I tried working with namespaces and simpleXML but still no result...any Ideas?
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header />
    <SOAP-ENV:Body>
        <ns3:GetDistrictByAddressResponse xmlns:ns3="http://il/co/bar/webservices/getdistrictbyaddress">
            <TimeFrameTable>
                <CustomerNumber>250</CustomerNumber>
                <Row>
                    <WindowDate>10052016</WindowDate>
                    <WeekDay>Sunday</WeekDay>
                    <FromHour>1130</FromHour>
                    <ToHour>1430</ToHour>
                </Row>
                <Row>
                    <WindowDate>10052016</WindowDate>
                    <WeekDay>Sunday</WeekDay>
                    <FromHour>1430</FromHour>
                    <ToHour>1730</ToHour>
                </Row>
            </TimeFrameTable>
        </ns3:GetDistrictByAddressResponse>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

A: xpath is your friend:
xpath('//Row');

Full example:
$soap = <<< LOL
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header />
    <SOAP-ENV:Body>
        <ns3:GetDistrictByAddressResponse xmlns:ns3="http://il/co/bar/webservices/getdistrictbyaddress">
            <TimeFrameTable>
                <CustomerNumber>250</CustomerNumber>
                <Row>
                    <WindowDate>10052016</WindowDate>
                    <WeekDay>Sunday</WeekDay>
                    <FromHour>1130</FromHour>
                    <ToHour>1430</ToHour>
                </Row>
                <Row>
                    <WindowDate>10052016</WindowDate>
                    <WeekDay>Sunday</WeekDay>
                    <FromHour>1430</FromHour>
                    <ToHour>1730</ToHour>
                </Row>
            </TimeFrameTable>
        </ns3:GetDistrictByAddressResponse>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
LOL;
$xml = simplexml_load_string($soap);
foreach ($xml->xpath('//Row') as $item)
{
    print_r($item);
}

Output:
SimpleXMLElement Object
(
    [WindowDate] => 10052016
    [WeekDay] => Sunday
    [FromHour] => 1130
    [ToHour] => 1430
)
SimpleXMLElement Object
(
    [WindowDate] => 10052016
    [WeekDay] => Sunday
    [FromHour] => 1430
    [ToHour] => 1730
)

Ideone Demo


text:
Q: Function testing for primes not working as needed It's supposed to find out if the given input is a prime number or not.
def is_prime(x):
    if x <= 1:
        return False
    elif x == 2 or x == 3:
        return True
    else:
        for n in range(2, x-1):
            if x % n == 0:
                return False
            else:
                return True

But
is_prime(9)

gives True where it should return False.
I can't find the bug, need help.

A: You return True the moment you find a factor that doesn't divide x evenly. 2 doesn't divide 9 so you return True then:
>>> x = 9
>>> n = 2
>>> if x % n == 0:
...     print False
... else:
...     print True
...
True

You need only return True when you determined that no factors exist, so outside your loop:
for n in range(2, x-1):
    if x % n == 0:
        return False
return True

You don't need to test up to x - 1, testing up to int(x ** 0.5) + 1 is enough (so up to the square root):
def is_prime(x):
    if x <= 1:
        return False
    if x in (2, 3):
        return True
    for n in range(2, int(x ** 0.5) + 1):
        if x % n == 0:
            return False
    return True


text:
Q: Wordpress custom table - get data out a foreach loop What I'm trying to achieve is:
I have a custom table with several rows.
Every row is an item linked with a page (the "page" field of the row is the name of a page), so that when I open a page I get all the items linked to that page.
I managed to get the rows corresponding to the page name. But I don't know how to manage the array.
The idea is to pass the variables to a page template, in order to automatically fill is with the correct data.
global $wpdb;
$mytitle = get_the_title();

$results = $wpdb->get_row($wpdb->prepare('SELECT * FROM wp_mytable WHERE page = %s', $mytitle));

$item-list = array();

foreach ($results as $r)
{
    $item-name = $r->name;
    $item-description = $r->desc;

    $item-list = "some html code with $item-name and $item-description";
}

In the page template I will just <?php echo $item-list; ?> in order to get all the items of that page.
But it doesn't seem to work.
Any help will be appreciated.
Thanks.

A:
If you want to get multiple data then you should use get_results()
  instead of get_row().

Try this code.
global $wpdb;
$mytitle = get_the_title();

$results = $wpdb->get_results($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'mytable WHERE page = %s', $mytitle));

$item_list = '
';
foreach ($results as $r)
{
    $item_name = $r->name;
    $item_description = $r->desc;
    $item_list .= '
' . $item_name . ' ' . $item_description . '
';
}
$item_list .='
';

Now $item_list holds the list HTML so to use it by echoing it as <?php echo $item_list; ?>.
Hope this helps!


text:
Q: Angular Date filter is not workig in firefox I am using date filter to format my date in my angular application.
In Firefox, I'm getting the date value as

undefined NaN, NaN NaN:NaN:NaN PM

In Chrome its works perfectly as

Jun 25, 2014 7:22:47 AM

My code is as follows.
var formatDate = new Date(info.list[i].date);
var newDate=$filter('date')(formatDate, 'medium');

How do I get it to work in Firefox?

A: I ran into this issue and found that the problem was Chrome/Opera and Firefox/Safari have different tolerances for creating a new Javascript Date object.
This works in Chrome and Opera, but not Firefox and Safari:
var myDate = new Date("2014-08-12 11:46:26.509")

This works in all mentioned browsers:
var myDate = new Date("2014-08-12T11:46:26.509")

Once I had a proper Date object created, the AngularJS date filter works as expected.

A: There is a moment.js library that facilitates dates parsing and that works cross-browser.
I also had a problem with NaNs in firefox and I was using
var myDate = Date.parse(date);

for Date creation. Switched to:
var myDate = moment(date).toDate();

and everything works flawlessly.


text:
Q: largets level set Consider the set
$$S=\{x,y,z|2x^2+y^2+z^2+xz<5\}$$
how can we find the largest level set of $S$ on $x-y$ plain? basically I look for a compact set $\bar{S}(x,y)$ such that every $x,y\in S$ is also in $\bar{S}$.  Is the following correct?
the max of x when $y=0$ and $x,y,z\in S$ happens when
$$4x+z=0$$
as a result we can conclude that
every $x,y\in S$ also belongs to
 $$14x^2+y^2<5$$

A: The projection on the $XOY$-plane is defined by the equations $X=x,Y=y,Z=0.$ Therefore, the projection of $S$ on the plane $XOY$ is defined by the inequality $$2X^2+Y^2<5.$$ The commands of Maple $$with(plots): with(plottools):$$ $$P := implicitplot3d(2*x^2+x*z+y^2+z^2 < 5, x = -4 .. 4, y = -4 .. 4, z = -4 .. 4, numpoints = 10^4, style = surface); $$ $$ Q := project(P, [[0, 0, 0], [1, 0, 0], [0, 1, 0]]):display(Q);$$ confirm that.


text:
Q: latest MYSQL Connector for RPI3 I have 12 other RPI3 that connect to my database with no issues and I just did a brand new install on a SD card using Raspberry pi imager_1.7.3.exe.  I installed the default Debian 32bit OS.  After installing I noticed that the python version they are using is 3.9.2.  I have my python program running with no issues until I get to connecting to the mysql server.  I get  the error. NameError: name 'mysql' is not defined
On my older RPI I had to install to the python3 and pip3.  Is there some install that I need for the latest version of Debian. I did the install of mysql connector using "pip install mysql-connector-python" and tried "python -m pip install mysql-connector" and I get this result on terminal
Requirement already satisfied: protobuf<=3.20.1,>=3.11.0 in ./.local/lib/python3.9/site-packages (from mysql-connector-python) (3.20.1)
I try running my program and I get the same error
NameError: name 'mysql' is not defined
What am I doing wrong.
python --version
Python 3.9.2
I can type python in terminal and type "import mysql.connector" and there is no error.  That tells me the connector imported.  when I get to the following code it fails saying "NameError: name 'mysql' is not defined"
mydb = mysql.connector.connect(host="108.190.xxx.xxx",user="xxxx",password="xxxxx",database="xxxxx")


text:
Q: make marker fill_alpha value-dependent in Bokeh In Bokeh, is it possible to have the marker alpha vary with values in a specified field?
For example, to vary color and marker by a field:
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.transform import factor_cmap,factor_mark

df = some dataframe
palette = ['#440154', '#404387', '#29788E', '#22A784', '#79D151', '#FDE724']
bok_sym = ['circle','asterisk','square_x','circle_x','diamond','hex']
cat_lst = list(df['cat_field'].unique())

df_cds = ColumnDataSource(data=df)

fig = figure(some kwargs)
fig.scatter(x='x',y='y',
            source = df_cds,
            marker = factor_mark('cat_field',bok_sym,cat_lst)
            fill_color = factor_cmap('cat_field',palette,cat_lst),
           )
show(fig)

There does not appear to be a similarly explicit function for alpha, but bokeh.transform does provide a generic transform
https://docs.bokeh.org/en/latest/docs/reference/transform.html
Which I've attempted with the following additions:
from bokeh.transform import transform

alph_lst = [0.2,0.9,0.9,0.9,0.9,0.9]

fig.scatter(x='x',y='y',
                source = df_cds,
                marker = factor_mark('cat_field',bok_sym,cat_lst)
                fill_color = factor_cmap('cat_field',palette,cat_lst),
                fill_alpha = transform('cat_field',dict(zip(cat_lst,alph_lst))),
               )

But without success.
Cheers
EDIT:
I'll note that I've already (unsuccessfully) tried to pass transparency as part of the hex code:
palette = ['#44015433', '#404387E6', '#29788EE6', '#22A784E6', '#79D151E6', '#FDE724E6']

A: As you stated in your question you can definitely achieve this with a custom Transform. They're a little cumbersome to wrap your head around (in my opinion) but hopefully this code should clear it up.
Essentially you need 3 steps create a custom javascript function and apply it to a field name in bokeh:

*

*Write javascript code that achieve the transformation you want. In our case we're just mapping categorical values to alpha levels in a dictionary.

*Put this javascript snippet into a CustomJSTransform object, feeding it the necessary arguments as a dictionary. In this case I built the factor -> alpha mappings in python and passed it into javascript. We used the vfunc argument because we want to apply this transformation to each instance of a category in our data.

*In your call to the plot function p.scatter use the transform function to tie your specified column name to your custom transformation. In this case alpha = transform("cat_field", categorical_alpha_transformer)
import pandas as pd
import numpy as np

from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.transform import factor_cmap, factor_mark, transform
from bokeh.models.transforms import CustomJSTransform
from bokeh.io import output_notebook, show

output_notebook()

v_func  = """
var new_xs = new Array(xs.length)
for(var i = 0; i < xs.length; i++) {
    new_xs[i] = alpha_map[xs[i]]
}
return new_xs
"""

df = pd.DataFrame({
    "cat_field": list("abcdef"),
    "x": list(range(6)),
    "y": list(range(6)),
})

palette = ['#440154', '#404387', '#29788E', '#22A784', '#79D151', '#FDE724']
bok_sym = ['circle','asterisk','square_x','circle_x','diamond','hex']
alphas = [.1, .25, .4, .55, .7, .85, 1]
cat_lst = list(df['cat_field'].unique())

alpha_map = dict(zip(cat_lst, alphas)) # {"a": .1, "b": .25, ... "f": 1}
categorical_alpha_transformer = CustomJSTransform(args={"alpha_map": alpha_map}, v_func=v_func)

df_cds = ColumnDataSource(data=df)

fig = figure(width=250, height=250)
fig.scatter(
    x='x',
    y='y',
    source = df_cds,
    marker = factor_mark('cat_field', bok_sym, cat_lst),
    fill_color = factor_cmap('cat_field', palette, cat_lst),
    size=20,
    alpha = transform("cat_field", categorical_alpha_transformer)

)

show(fig)


text:
Q: Best way to implement "dashboard" within custom list? My dashboard in this case is simply a waterfall of roughly 60 activities that need to be completed for each item. Ideally, people will be able to switch to the dashboard content type to see the status of each activity for each item.
Each item already has several content types representing "tabs" for their respective areas.
Each activity needs a status and optional comments.
We're using SP Foundation 2010, and I'm only a site owner (sucks, I know).
There must be a better way than just making a bunch of columns, then adding them to the "dashboard" content type?

A: Although I'm not sure what you mean by "roughly 60 activities", but if all you need to do are display some links or images, you could create an html page with links to your "activities" and load it into a content editor web part.  You need to save your html page somewhere in the site-collection libraries, and then the CEWP can display it seemlessly without any iframe.
Then, you can edit the html however you want, and no matter what page it appears on, the edit is made for everywhere you've used it.
You should be able to do this with Sharepoint Foundation.


text:
Q: Position TextBox in Chart in Excel to the top / left -4 I have a chart in excel. Inside this chart there is a textbox. I want to position this textbox to the upper left corner of the chart.
When I do this manually and read out the properties .Top and .Left I get -4 as a response.
If I try setting these two properties to -4 the textbox goes to positions 0 and not -4.
Why cant I position the texbox to the upper left corner of the chart?
Is here some outer margin of the textbox or an inner margin of the chart / chartarea?
Here is some code to test it with any chart, in which you inserted a textbox:
Sub TextBoxPositionUpperLeftCorner()
    Dim cho As ChartObject
    Dim sh As Shape

    For Each cho In ActiveSheet.ChartObjects
        For Each sh In cho.Chart.Shapes

            'reading out the position
            Debug.Print "Top: " & sh.Top
            Debug.Print "Left: " & sh.Left

            'setting the position
            sh.Top = -4
            sh.Left = -4

        Next
    Next
End Sub

A: Seems like you can't set Top/Left to negative numbers.
But you can increment the position to achieve that:
Sub TextBoxPositionUpperLeftCorner()
Dim cho As ChartObject
Dim sh As Shape

For Each cho In ActiveSheet.ChartObjects
    For Each sh In cho.Chart.Shapes

        'reading out the position
        Debug.Print "Top: " & sh.Top
        Debug.Print "Left: " & sh.Left

        sh.IncrementTop -(sh.Top + 4)
        sh.IncrementLeft -(sh.Left + 4)

         'reading out the position
        Debug.Print "Top: " & sh.Top
        Debug.Print "Left: " & sh.Left

    Next
Next

EDIT: after a little more testing, the most negative you can go even with this approach is -4/-4.


text:
Q: How to get serverside filename in clientside while using AsyncFileUpload I'm using AsyncFileUpload for uploading files, before saving file on server, i rename the selected file. How can I get this new file name in the client side?
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
                    OnUploadedComplete ="UploadFile1"
                    OnClientUploadComplete="uploadComplete" ThrobberID="myThrobber" />

Client-side script:
   <script>
   function uploadComplete(sender, args) {
         var fileExtension = args.get_fileName();
   }
   </script>

Server-side script:
Protected Sub UploadFile1(ByVal sender As Object, ByVal e As System.EventArgs)

    Dim fileuploadreceive1 As String = AsyncFileUpload1.PostedFile.FileName
    Dim strExtn As String = System.IO.Path.GetExtension(fileuploadreceive1).ToLower

    Dim filename1 As String = Path.GetFileName(fileuploadreceive1)
    filename1 = "uld" & Math.Round(Rnd() * 2366) & filename1 'changing original file name
    Dim fileuploadpath1 As String = Server.MapPath("~") & "\gallery\"

    If (strExtn = ".png") Or (strExtn = ".jpg") Or (strExtn = ".gif") Then
        AsyncFileUpload1.PostedFile.SaveAs(Path.Combine(fileuploadpath1, filename1))

    End If
End Sub

A: were you talking about something like:
<%= Page.ResolveClientUrl("~/images/MemoEditor_ABCtoolbar.png") %>

This will get the servers name for it, and then pass what it is called to the client.  You can wrap that in some simple javascript or in this example, put it in the src of an image tag.
var x = '<%= Page.ResolveClientUrl("~/images/MemoEditor_ABCtoolbar.png") %>';


text:
Q: How can I avoid Firefox and Internet Explorer using different leadings when rendering this HTML? Firefox 50 and Internet Explorer 11 are using different amounts of leading (space between lines) when rendering the same HTML code. How can I control the leading so that it is the same in both browsers?
HTML

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Screenshot:

A: Browsers naturally assign different css properties by default. You can clear everything ( or almost everything ) and then reassign it manually. This may also include manually setting the line-height property.
This is known as a "CSS Reset" however, use it sparingly and only use what's needed.

A: Are you using Normalize CSS in your style sheet? One thing Normalize does, among many others, is it "corrects the line height in all browsers."

Normalize.css is a modern, HTML5-ready alternative to CSS resetsmakes
  browsers to render all elements more consistently and
  in line with modern standards. It precisely targets only the styles
  that need normalizing. http://necolas.github.io/normalize.css/

You may also need to target IE11 with specific rules in your style sheet: Detecting IE11 using CSS Capability/Feature Detection


text:
Q: Add layers to a PSD file using ImageMagick I have a lot of JPEG files and I want to add them as layers to a PSD file using ImageMagick
I found several scripts to do the opposite, extract the layers from a PSD file. I don't want that.
I just want to take several JPEG pictures and add them as layers to a PSD (photoshop) file and name those layers as the JPEG file name. I found a way to create composite images with ImageMagick but all the examples I saw create a PNG or GIF file. I need to create a PSD layered file.

A: A couple of notes first:
1/ The first layer in a psd file is all the layers merged and you would need to create that first.
2/ For some reason the first layer using the code below drops the first layer e.g image1.png so create a blank layer to use as the first layer.
3/ The layers in my test were renamed to L000001 etc.
The answer to the first part of your question is:
convert image1.png image2.png image3.png

But I do not know how to keep the image names as the layer names


text:
Q: Strange error An error just occured please try your request again: in yii2 application H have a yii2 application running on a server with the following specification
yii2 version: 2.0.39.3
server : vultr VPS centos 8, running PHP version 7.2.24
web server NGINX ginx version: nginx/1.14.1

I have used it for months and everything works fine but in the past 3 days  suddenly sometime it An error just occured please try sometime at the top of the page and sometime at the end of my page. This randomly appear when i refresh my server I am not sure. This happen whenever a request to the server is made and if an ajax request is made the server will receive the request but the client will receive and error message instead of a reply from he server, and also the message change the layout of the page it appears on. I have no clue as to where this could come from as i didn't do any server update of recent. Any help on this would be appreciated. attached is an image of what the error looks like from the page

A: Seems this errors related with Google Site Verification API. Check if you've not enabled "Maintenance Mode" etc.


text:
Q: FieldError while using Q objects- cannot resolve keyword __ into field Fairly new to django.
contructign view for index page . using 'complex lookups using Q objects' as in documentation.
Coming across the following error

Request Method:   GET Request URL:
    http://127.0.0.1:8000/music/?q=wretched Django Version:     1.11.12
  Exception Type:   FieldError Exception Value:
Cannot resolve keyword 'album_title_icontains' into field. Choices
  are: album_favorite, album_logo, album_title, artist, genre, id, song,
  user, user_id
Exception Location:
    /usr/lib64/python2.7/site-packages/django/db/models/sql/query.py in
  names_to_path, line 1352 Python Executable:   /usr/bin/python Python
  Version:  2.7.15

the function view causing problem is index() (given below)
def index(request):
    if not request.user.is_authenticated():
        return render(request, 'music/login_form.html')
    else:
        albums= Album.objects.filter(user=request.user)
        songs=Song.objects.filter(album=albums)
        num= Album.objects.filter(user=request.user).count()
        req= request.GET.get("q")
        if req:
            albums= albums.filter(
                Q(album_title_icontains=req) |
                Q(artist_icontains=req)
            ).distinct()
            songs=songs.filter(
                Q(song_title_icontains=req)
            ).distinct()
        context={
        'object_list': albums,
        'num': num,
        'songs': songs
        }
        return render(request, 'music/index.html', context)

the models.py file file is as given below
from __future__ import unicode_literals

from django.contrib.auth.models import Permission, User
from django.db import models
from django.core.urlresolvers import reverse

class Album(models.Model):
    user= models.ForeignKey(User, default=1)
    artist= models.CharField(max_length=100)
    album_title= models.CharField(max_length=200)
    genre= models.CharField(max_length=50)
    album_logo= models.FileField()
    album_favorite= models.BooleanField(default=False)

    def get_absolute_url(self):
        return reverse('music:detail',kwargs={'pk':self.pk})

    def __str__(self):
        return self.album_title+' by '+ self.artist

class Song(models.Model):
    album= models.ForeignKey(Album, on_delete=models.CASCADE)
    song_title= models.CharField(max_length=200)
    audio_file= models.FileField(default='')
    is_favorite= models.BooleanField(default=False)
    def __str__(self):
        return self.song_title

    def get_absolute_url(self):
        alb= self.album
        return reverse('music:detail',kwargs={'pk':alb.pk})

Help would be much appreciated. Thanks in advance.

A: you need dundee('__') double underscore to use the filters.
albums= albums.filter(
                Q(album_title__icontains=req) |
                Q(artist__icontains=req)
            ).distinct()
            songs=songs.filter(
                Q(song_title__icontains=req)
            ).distinct()

A: Your view is correct, just a minor typo. you just needed Double-Underscore :-
__
 for your lookups. From docs
Correct - Views.py
def index(request):
if not request.user.is_authenticated():
    return render(request, 'music/login_form.html')
else:
    albums= Album.objects.filter(user=request.user)
    songs=Song.objects.filter(album=albums)
    num= Album.objects.filter(user=request.user).count()
    req= request.GET.get("q")
    if req:
        albums= albums.filter(
            Q(album_title__icontains=req) |
            Q(artist__icontains=req)
        ).distinct()
        songs=songs.filter(
            Q(song_title__icontains=req)
        ).distinct()
    context={
    'object_list': albums,
    'num': num,
    'songs': songs
    }
    return render(request, 'music/index.html', context)


text:
Q: Solve the following PDE: $(1+\sqrt{z-y-x})z'_x+z'_y=2$ Solve the following PDE: $(1+\sqrt{z-y-x})z'_x+z'_y=2$ given that $z(x,2x)=2x$.
I want to explain to you how we were taught to solve these at class, and this method seemed to work with other exercises, but with this one it seems to fail.
We rewrite the question:
$\frac{d x}{1+\sqrt{z-y-x}}=\frac{d y}{1}=\frac{d z}{2}$
We can see that $2dy=dz$, so $2y-z=C_1$ where $C_1$ is some constant. We define the function $\psi_1(x,y,z)=2y-z$. We called this function "An integral of the system". We need to find another one. We can see that
$dz=2dy, dy=dy, dx=(1+\sqrt{z-y-x})dy$, and so $dz-dy-dx=-\sqrt{z-y-x}dy$
Divide to get $\frac{dz-dy-dx}{-\sqrt{z-y-x}}=\frac{d(z-y-x)}{-\sqrt{z-y-x}}=dy$
Integrate to get the second integral, $y+2\sqrt{z-y-x}=C_2$, let's call it $\psi_2(x,y,z)=y+2\sqrt{z-y-x}$. So now we have our 2 integrals $\psi_1$ and $\psi_2$.
For our method to work, we need to apply the initial value to our integrals, meaning find $\psi_1(x,2x,z)$ and $\psi_2(x,2x,z)$. Let's call them $\bar\psi_1$ and $\bar \psi_2$ respectively.
So $psi_1(x,2x,z)=4x-z=\bar \psi_1$ and $\psi_2(x,2x,z)=2x+2\sqrt{z-3x}=\bar \psi_2$
We can now (in theory, that's what worked in previous exercises) represent $x$ and $z$ as functions of $\bar \psi_1$ and $\bar \psi_2$: $x=f(\bar \psi_1,\bar \psi_2)$ and $z=g(\bar \psi_1,\bar \psi_2)$
Now the final step to get the solution, we apply that to the initial value: $z(x,2x)=2x$, but $x=f(\bar \psi_1,\bar \psi_2)$ and $z=g(\bar \psi_1,\bar \psi_2)$
And so:
$g(\bar \psi_1,\bar \psi_2)=2f(\bar \psi_1, \bar \psi_2)$ and plugging in $g(\psi_1,\psi_2)=2f(\psi_1,\psi_2)$ we can find either an explicit or an implicit term for $z$.
There is no doubt that this method works, as it solved all of our other exercises, but in this one, I'm having trouble representing $x$ and $z$ as functions of $\bar \psi_1$ and $\bar \psi_2$.
We know that $z=4x-\bar \psi_1$, which would mean $2x+2\sqrt{4x-\bar \psi_1-3x}=\bar \psi_2$ and I wasn't able to extract an explicit term for $x$ from that equation.

A: Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dy}{dt}=1$ , letting $y(0)=0$ , we have $y=t$
$\dfrac{dz}{dt}=2$ , letting $z(0)=z_0$ , we have $z=z_0+2t=z_0+2y$
$\dfrac{dx}{dt}=1+\sqrt{z-y-x}=1+\sqrt{z_0+t-x}$
Let $u=z_0+t-x$ ,
Then $x=z_0+t-u$
$\dfrac{dx}{dt}=1-\dfrac{du}{dt}$
$\therefore1-\dfrac{du}{dt}=1+\sqrt u$
$-\dfrac{du}{dt}=\sqrt u$
$dt=-\dfrac{1}{\sqrt u}~du$
$t=f(z_0)-2\sqrt u$
$y=f(z-2y)-2\sqrt{z-y-x}$
Case $1$: $z(x,y=2x)=2x$ :
$2x=f(-2x)-2\sqrt{-x}$
$f(-2x)=2\sqrt{-x}+2x$
$f(x)=\sqrt{2x}-x$
$\therefore y=\sqrt{2z-4y}+2y-z-2\sqrt{z-y-x}$
Case $2$: $z(y=x,2x)=2x$ :
Consider $z=2y+F(2\sqrt{z-y-x}+y)$ :
$2x=2x+F(2\sqrt{-x}+x)$
$F(2\sqrt{-x}+x)=0$
$F(x)=0$
$\therefore z=2y$


text:
Q: 3D exporting and Qgis2threejs plugin I have a .shp-file of some buildings with a sheet in an attribute table of their height. I want to extrude them using a Qgis2threejs plugin, but since a sheet of height is shown as a type of QString, the plugin can't recognize it and the buildings can't be extruded.
I have tried to export a database as a .csv-file, but the Excel is locked and it can't be modified.
Any alternative approaches?

A: If the heights are in a column of the attributes table, but stored as QString type, you can convert them in a new numeric type column.

*

*Add a new field with the Decimal number (real) type and the desired length and precision in the attribute table.

*Populate that field in the Field Calculator with the expression:
to_real("height")
Where "height" is the name of the string type field.


text:
Q: Trying to get this to work on a button (on click) so that it fills/updates another field in the same row function myFunction() {
    var w = document.getElementById("QTY_r.0").value;
    var y = document.getElementById("Cycle.0").value;
    var z = document.getElementById("Requestedr.0").value;
    var x = +z - +w + +y
    document.getElementById("Returnedr.0").value = x
}

function calculate1() {
    cycle = Number(this.getField("Cycle.0").value);
    requested = Number(this.getField("Requestedr.0").value);
    qty = Number(this.getField("QTY_r.0").value);
    Number(this.getField("Returnedr.0").value = String(Requested - Total + Cycle);
}

("Returned.0").value = Number(this.getField("Requestedr.0").value) - Number(this.getField("QTY_r.0").value) + Number(this.getField("Cycle.0").value);


text:
Q: Making Text an Image in flutter Ok, SO i have a complicated question
So im making this list where there is a checkbox and some text I was hoping i could add an image to be tricked int to thinking its textThe problem is that Whenever i add some text, the image gets added with itI
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
void main() {
  runApp(new MyApp(
    title: new Text("My App"),
    someText: new Text("Some Text..."),
  ));
}
class MyApp extends StatefulWidget {
  MyApp({this.title, this.someText});

  final Widget title, someText;

  @override

_MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  File _image;

  Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    setState(() {
      _image = image;
    });
  }

  TextEditingController eCtrl = new TextEditingController();
  bool showDialog = false;
  List<String> textlist = [];
  List<bool> textChkBox = [];

  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: widget.title,
          actions: <Widget>[
            new IconButton(
                icon: new Icon(Icons.add_comment),
                onPressed: () {
                  setState(() {
                    showDialog = true;
                  });
                }),
            ),
            new FloatingActionButton(
              onPressed:  getImage,
              tooltip: 'pick Image',
              child: new Icon(Icons.camera),
            ),
          ],
        ),
        body: new Column(
          children: <Widget>[
            showDialog == true
                ? new AlertDialog(
              title: new Text("Alert Dialog"),
              content: new TextField(
                controller: eCtrl,
                decoration: new InputDecoration.collapsed(hintText: "ADD XYZ"),
                maxLines: 6,
                onSubmitted: (String text) {},
              ),
              actions: <Widget>[
                new FlatButton(
                    onPressed: () {
                      setState(() {
                        showDialog = false;
                        textlist.add(eCtrl.text);
                        textChkBox.add(false);
                        eCtrl.clear();
                      });
                    },
                    child: new Text("OK"))
              ],
            ) : new Text(""),
            new Flexible(
                child: new ListView.builder(
                    itemCount: textlist.length,
                      itemBuilder: (BuildContext ctxt, int index) {
                        return new Column(children: <Widget>[
                          new Checkbox(
                             value: textChkBox[index],
                             onChanged: (bool newValue) {
                               textChkBox[index] = newValue;
                               setState(() {});
                             },
                          ),
                          new Text(textlist[index]),
                          new Card(
                            child: _image == null ? new Text("-")
                            : new Image.file(_image),
                          ),
                        ]
                      );
                    }
                )
            )
          ],
        ),
      ),
    );
  }
}

As you can see it displays The checkbox, Text, and Image at the same time


text:
Q: MYSQL which version of update is faster I'm coding queries for a MYSQL database i created. I have a very large amount of rows and i'm asking myself which version of update is faster.
Is faster:
a) Version with WERE
UPDATE table t1 JOIN table t2
SET t1.c1 = 'something'
WHERE t1.c1 = t2.c1

or
b) Version without WERE
UPDATE table t1 JOIN table t2 on t1.c1 = t2.c1
SET t1.c1 = 'something'

?
The question could be also: is it better to specify the "CONDITION" in the JOIN of two tables or in the WERE statement in an update in MYSQL to get faster performance?


text:
Q: PictureCallback is being fired from main thread I'm using in my app android.hardware.Camera to take picture.
I'm wondering why the PictureCallback's method that i provided to function is being fired from the Main thread ?
how can i fire this callback from background thread ?
thanks

A:
I'm wondering why the PictureCallback's method that i provided to function is being fired from the Main thread ?

Because pretty much all callbacks to you are on the main application thread.

how can i fire this callback from background thread ?

You can't AFAIK. If you are doing something long with the picture (e.g., writing it to flash, streaming it over the network), fork your own thread from onPictureTaken(). Here is a sample project that uses an AsyncTask for this.


text:
Q: Logarithmic triangle inequality Assume that (X,d) is a metric space.
Is there a simple/smart way (e.g. using some convexity argument) to show shat:
$d^{*}(x,y) = ln(1+\frac{d(x,y)}{1+d(x,y)})$
is a distance, esp. that it does satisfy the triangle inequality?
Thus far I can only manage to prove it by using exp and brutally expanding/simplifying.
Thanks,
J.

A: Lemma: Given a concave function $f:[0, +\infty] \rightarrow \mathbb{R}$  s.t. $f(0)=0$ then $f$ is subadditive i.e. $\forall x,y \space f(x+y) \le f(x)+f(y)$.
You should also know that given a distance $d$, the function $d'=\frac{d}{1+d}$ is a distance; then is straightforward: take arbitrarily $x,y,z \in X$
$$
 d^*(x,z)=\ln[1+d'(x,z)]\le \ln[1+d'(x,y)+d'(y,z)]  \\
\stackrel{subadditivity}{\le} \ln[1+d'(x,y)]+\ln[1+d'(y,z)]=d^*(x,y)+d^*(y,z)
$$

Proof of lemma: https://en.wikipedia.org/wiki/Concave_function point 6 of "properties" section.


text:
Q: Why I need any type in typescript? We have a simple method in typescript
function identity(arg) {
    return arg;
}

This method gives a parameter and returns it and it will work by any type (int,string,bool and more).
We can also declare this method in another way:
 function identity(arg:any):any {
        return arg;
    }

This method gives a parameter and returns it and it will work by any type (int,string,bool and more).
What is the difference between the two ways? In other word what is benefit using of any type?

A: In your particular case, it doesn't matter. But

*

*If you have the strict flag on (or, by extension, the noImplicitAny flag), it will throw an error for the first, but not the second. Because an implicit any is not allowed.

*The reason they are the same is because TypeScript can't infer the type of the argument or the return type, so they are both inferred to any.

Any is your escape hatch from TypeScript, it means "I don't know what type this is, so anything I do with it is acceptable, any property on it implicitly exists (and also has a type of any), I can call it with any parameters, and I can also new it.
It is recommended that you minimize your use of anys, implicit or explicit, because then you lose some of the benefit that TypeScript affords.

A: any is like an anonymous type, not like Object. When using any, the compiler does minimal type checking since it doesn't know your variable's members.
Example:
var var1: any;
var var2: Object;

var1.whatever(); // The compiler trusts you
var2.whatever(); // Compiler throws an error

As you can see in the example, you can handle var1 however you want, but you can't mess with var2 except for its official members.
In your function, you can whatever you want with your arg, but if you specify a type for it then you'll be bound to use that type's members.


text:
Q: Where does "tin ear" come from Inspired by my own answer to How would deafening as punishment be carried out? at worldbuilding.se, I was thinking about the phrase "tin ear", meaning tone deaf, or (Collins) an inability to perceive differences in musical sounds. Merriam-Webster has a deafened or insensitive ear, which doesn't fit their example (My wife is a talented musician, but I have a tin ear) very well.
We've discussed the meaning before but not the etymology.  There's some speculation at that last link about ear trumpets, and more here. Dictionary.com  has a few historical records, but I can't find anything definitive.
So: Where does tin ear come from?  Speculation I've seen includes:

*

*Ear trumpets made of tin (this would seem more logical if it just meant deaf)

*Tin (plate) as cheap and nasty

*Tin instruments or dropped items made of tin sounding horrible

*A tale of using a piece of tin on a morse buzzer to amplify the sound

*Tinnitus

A: The earliest record I can track of the use in print is in the novel Titan:A Romance, by Jean Paul Richter, published in translation from the German in 1863 and in the original language between 1800 and 1803.
Several sections of the text refer to a gentleman's frustration at the loss of his ear trumpet:

'"My ear, madam," he continued, "cannot be found again at all among the domestics; I have that to tell you." For he had today posted himself upon a law-giving Sinai, and thundered into the ears of the service assembled at its foot the inquiry after his own ear, "because I must believe," he had said to them, "that you, for very good reasons, have stolen it from me."
...
'He saw through all, heard all, though they had his away his ear-trumpet.'

the saga continues later in the book

'her astonishment can be compared with the greater astonishment of her
  husband, who happened to have been screwing in in the third chamber
  his tin ear, -made by Schropp of Magdeburg,- in order to listen to the
  servants, and who now caught a number of things.  Nevertheless, the
  double-ear, with the broad meshes of its nocturnal lark-net, had only
  fished up from Augusti's low, whispering, courtly lips single, long,
  proper names, -such as Roqairol and Zesara.' Hardly had the soft
  spoken Lector gone out, when he stepped gayly into the chamber, with
  his ear in his hand and demanded of her a report of the reports.

and continues...

First he inquired,- for he had been listening in vain,- in a very exasperated manner, of the Minister's lady, where she had stowed away his ear (it was the tin duplicate ear, wherein, as in a Venetian' lion's-head, all mysteries and accusations of the whole service and family met);...'

From this it seems clear that the American translator, Charles Timothy Brooks, was comfortable with the idea that his readers would understand the varied references 'tin ear' to refer to the same device as 'ear'and ear-trumpet'. I have no german so I'm not able to go to the original text to see what liberties may or may not have been taken with the translation in that regard. If anyone else can compare texts I'd be happy to hear and incorporate the results.
Seeing @RaceYouAnytime's answer, I thought it might be worth exploring whether it is the case that while 'tin ears' were ear trumpets, not all ear trumpets were 'tin ears'.
It is quite easy to picture the very obvious ear trumpets which we have all seen in cartoons and comedies, but there were also designs for small, discreet devices and the more money you had the fancier they could be.
This example is from 1830 and is described as an 'Artificial concha'

Bernard Becker Medical Library Image Gallery:  This delicate hearing device is molded of silver and gold plated and was molded to fit each individual user. It is lightweight (only 0.8 ounces) and can stay in the ear unsupported. The 2-3/8 x 3/4 inch opening is covered by a decorative filigree grill. The outer face of the device is a carved shell shape. Though designed to be barely visible when worn, this piece is beautifully crafted.

This device called an Otophone, was designed to make the wearer's ear stick out and dates from 1860.

This small curved silver device was designed to make the ear protrude slightly to facilitate the collection of sound waves.

pair of gilded ear trumpets made by F C Rein, London c1850

All of these are devices are 'worn in', rather than 'held to' the ear and I would speculate that it could be something of this nature which people were thinking of when giving the alternative name 'tin ear' to a cauliflower ear, particularly when considering the Titan reference to screwing in the device..

A: It appears to come from your first suggestion

*

*Ear trumpets made of tin.

Having a tin ear appears to have been an expression that started out meaning somebody who was deaf, and its meaning shifted to somebody who was tone deaf. This next is pure speculation, but this semantic shift could have started with the expression a tin ear for music, which is still occasionally used.
I give some excerpts in support of this etymology: First, from the magazine Mixer and Server (1915), an excerpt that makes it clear that having a tin ear means being hard of hearing:

If that fellow working at the trade across the street, whom you have been trying to secure as a member of your local union, and who seems to listen but seldom makes comment on anything said to him, is given closer inspection, it may disclose that he has a tin ear, and that you will have to offer him something in the shape of reading matter to gain his attention.

Second, showing that tin ear meant ear trumpet, a 1915 article in American Playwright titled The Tin Ear in the Drama and Elsewhere. This article talks about Thomas Edison's invention of the audiophone, an early hearing aid, and complains about this invention not being available to the public. In these excerpt, you can see that tin ear means an ear trumpet, and a man with a tin ear is somebody who uses an ear trumpet, i.e. somebody who is hard of hearing.

When the audiphone was first announced the old reliable tin ear-trumpet was laid away ...
Perhaps the wizard [Mr. Edison, the "wizard of Menlo Park"] doesn't understand the disadvantages under which a man with a tin ear labors, and we have seriously undertaken to let him know.
We are, moreover, tired of addressing the entire human race when we talk into a tin ear, and it is humiliating to be supposed by the person addressed to be talking about the crops, when you are discussing the doctrine of the transmigration of souls.

A: OED first attests "tin ear" in the sense of musical impairment in 1935.

A player has a 'tin ear' when his intonation is poor and his playing is mechanical.

*

*Peabody Bulletin (Baltimore) · 1935

I found three senses of "tin-ear" in the period shortly prior to this attestation.  The most frequent by far seemed to be "tin ear" meaning a boxer's damaged ear from fighting, similar to "cauliflower ear."

*

*A tool used for listening to submarine activity in military combat.

The listening gear, or "tin ears" as the sailors call them, established that the submarine was lying helpless at the bottom.

*

*Chillicothe Gazette (Chillicothe, Ohio)12 Nov 1918, Tue (paywall)

*A tool used for improved hearing.

Senator Fred Dumont Smith, from Edwards county, thought for a time yesterday that his senatorial career was come to an end.  There seemed to be a conspiracy to handicap him.  Senator Smith is deaf and he uses a small metal ear trumpet.  He calls it his "tin ear."

*

*The Chanute Daily Tribune (Chanute, Kansas)12 Jan 1905, Thu

*As mentioned, the most common use of the term around the early 1900's related to the damaged ears of boxers.
I would suggest that the frequency with which "tin ear" meant one damaged by pugilism means it likely played a role in the later meaning related to musical deficiency.

About eight out of every ten fist fighters you see nowadays own the "cauliflower," or "tin" ear; an ear so battered and punched by the bludgeonings of five-ounce gloves that it isn't really an ear any more at all, but just a misshapen chunk of cartilage clinging to the side of the head.

*

*"Prize Fighteres Disdain "Tin Ears," Most Boxers, However, Get Those Ears." El Paso Herald (El Paso, Texas)14 Jan 1916, Fri (paywall)

It's worth noting that having "tin ears" in the boxing sense generally implied a hearing deficiency as a medical result of the constant bettering.  A headline in 1915 reads out:

Matt Wells in America, Talks War and Sports As They Affect England
Expects to Resume Boxing, Being Ineligible for Army on Account of Faulty Hearing, Due to His "Tin Ears" [emphasis mine]

*

*The Winnipeg Tribune (Winnipeg, Manitoba, Canada)19 May 1915, Wed
A 1935 article jokingly attributes "tin ear" to a husband's propensity not to listen.

There are times when every man seems to have what is popularly known as a "tin ear"--especially every married man.  In fact, a man's auditory nerve is almost as miraculous as his memory, which can be turned off or on at will, like a radio.

*

*"'Tin-Ear' Credited Every Married Man When Wife Talks", Helen Rowland. The Miami News (Miami, Florida)14 Nov 1935, Thu
My reason for linking the musical deficiency version of "tin ear" with the boxing meaning is that they both have a connotation of damage and are looked down upon as an impairment.  Furthermore, "tin ears" as in hearing aids are not the cause of deafness or hearing loss, but the fix for it.  Having tin ears as a boxer is a physical burden brought upon themselves.  I think that the sense in which it was used to describe the ears of boxers more easily translates to the sense related to lacking musical proficiency than does the hearing-aid etymology.


text:
Q: How can I determine a user's current location on a GPS path? I have a path of GPS coordinates that I'm drawing to a map.  I need to determine which point of the path the user is currently closest to.  I'm able to loop through nearby points on the path and determine which is the closest, but I'm having an issue.
Sometimes the path involves a return trip, so two parts of the path may be parallel.
What is the best way to tell whether the user is on the way out or returning?  They may launch my app at any point during the path, and it needs to be able to know what part of the path they're on.
The only solution I can think of is to use the direction they're moving and guess that they must be on whichever part of the path moves in that direction, but it seems like there has to be another way.
For clarification:  In the diagram below, how can I determine whether the user is at point A or point B of the path, if I can't assume that my app has been location-aware for the duration of their traveling the path?
Diagram

A: The solution is a combination of distance checking and direction checking.
First get all positions within a radius of 100m, then sort by distance.
Take the first which does not deviate by more than x degrees of current user direction.


text:
Q: Elasticsearch use icu_tokenizer from ICU Analysis plugin I am trying to install ICU Analysis plugin manually in Elasticsearch 1.4.0. I have downloaded elasticsearch-analysis-icu-2.4.1.jar, lucene-analyzers-icu-4.10.2.jar and icu4j-54.1.1.jar. The plugin appears normally in the console, but when I try to use icu_tokenizer, I get the following error:
NoClassDefFoundError[Could not initialize class org.apache.lucene.analysis.icu.segmentation.DefaultICUTokenizerConfig]

This class actually exists in lucene-analyzers-icu. Is there something I am missing?

A: Did you try using the plugin installer instead of downloading the jar files manually as suggested in the documentation?
./bin/plugin -install elasticsearch/elasticsearch-analysis-icu/2.6.0

Run the command and restart the server. The plugin will be registered and functional.

A: Document
sudo bin/elasticsearch-plugin install analysis-icu


text:
Q: python how do use filter and diff in a row? so basically in i need to remove objects in the dataframe who's column transaction_date (row containing datetime objects) doesnt streak by month (basically they need to have a consistent transaction_date row based on the month, so if one month is skipped inside the transaction_date row they're filtered out)
currently this is the code i've come up with
seconds_per_month = 2629746
sorted_df = dataframe.sort_values(by=["transaction_date"])
engaged_transactions = sorted_df.groupby(["username"]).filter(lambda x: (x["transaction_date"].diff().dt.total_seconds() <= seconds_per_month).all())

im trying to filter out users where one of their transaction_date row skipped a month however engaged_transactions becomes empty
how do i achieve this?


text:
Q: Не получается запустить локальный сервер (Python,Django) Создаю виртуальное окружение, устанавливаю в него django, активирую его.
После я перемещаюсь в директорию, где находиться файл manage.py, решаю, что для того, чтобы запустить сервер мне необходимо ввести: python manage.py runserver. Не прошло. Вот лог из командной строки:
(lol) R:\Новая папка (4)\lol\courses_django\courses_django>python manage.py runs
erver
C:\Users\artem\AppData\Local\Programs\Python\Python37-32\python.exe: can't open
file 'manage.py': [Errno 2] No such file or directory

(lol) R:\Новая папка (4)\lol\courses_django\courses_django>cd ..

(lol) R:\Новая папка (4)\lol\courses_django>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you
 apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
February 10, 2019 - 10:07:22
Django version 2.1.5, using settings 'courses_django.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper
 at 0x031F7E88>
Traceback (most recent call last):
  File "R:\Новая папка (4)\lol\lib\site-packages\django\utils\autoreload.py", li
ne 225, in wrapper
    fn(*args, **kwargs)
  File "R:\Новая папка (4)\lol\lib\site-packages\django\core\management\commands
\runserver.py", line 139, in inner_run
    ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls)
  File "R:\Новая папка (4)\lol\lib\site-packages\django\core\servers\basehttp.py
", line 203, in run
    httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
  File "R:\Новая папка (4)\lol\lib\site-packages\django\core\servers\basehttp.py
", line 67, in __init__
    super().__init__(*args, **kwargs)
  File "C:\Users\artem\AppData\Local\Programs\Python\Python37-32\lib\socketserve
r.py", line 452, in __init__
    self.server_bind()
  File "C:\Users\artem\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\sim
ple_server.py", line 50, in server_bind
    HTTPServer.server_bind(self)
  File "C:\Users\artem\AppData\Local\Programs\Python\Python37-32\lib\http\server
.py", line 139, in server_bind
    self.server_name = socket.getfqdn(host)
  File "C:\Users\artem\AppData\Local\Programs\Python\Python37-32\lib\socket.py",
 line 676, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 6: invalid
continuation byte

Работал с установленным python 3.7.2, с django 2.

A: Проблема в том, что имя вашего компьютера содержит кириллические символы. Да и в пути к проекту нежелательно иметь каталоги с русскими названиями.


text:
Q: Why is physical space equivalent to $\mathbb{R}^3$? Why is physical space equivalent to $\mathbb{R}^3$, as opposed to e.g.  $\mathbb{Q}^3$?
I am trying to understand what would be the logical reasons behind our assumption that our physical space is equivalent to $\mathbb{R}^3$ or 'physical straight line' is equivalent to $\mathbb{R}$ .
The set of reals $\mathbb{R}$  is a basically an algebraically constructed set, which is nothing but the completion of $\mathbb{Q}$, the set of rationals. For reference see here http://en.wikipedia.org/wiki/Construction_of_the_real_numbers. Now my question is what is the reason behind our approximation of the physical space by this abstract set. Why is this approximation assumed to be most suitable or good approximation?

A: The reals are simply chosen so that you don't have to worry about the existence of coordinates of points if you do geometry. If you use Q instead you get into a lot of trouble. Remember that geometry also provided one the first reasons to think about irrational numbers.
If you wonder whether "nature" uses reals to compute its evolution or if it's something else then this question is close to meaningless. Our models will very likely come to a point where we won't think of space as a manifold at all, so specifically not as a real manifold. Or in other words, there is no fundamental physical meaning to real numbers. They're just a convenience for us.


text:
Q: "Remember me" feature does not work when RD getaway is used The "remember me" feature does not work for me when I use RD gateway to connect to my workstation. Something forces me to explicitly type the credentials every time - I need to figure out what this something is.
I have the following scenario: There is workstation that is behind NAT and inaccessible from outside our company network.

*

*I can connect my my workstation from inside the network and Windows does save the credentials after changing the Credentials Delegation Group Policy.

Local Computer Policy\Computer Configuration\Administrative
  Templates\System\Credentials Delegation\
Allow Delegating Saved Credentials with NTLM-only Server
  Authentication

*Credentials saving also works when I connected to my company's network via VPN and then connect to workstation.

*Credential saving does not work when I connect to my workstation via RD gateway -- it says "The logon attempt failed" and forces manual credentials entering

The 3rd scenario is the one I'm interested in figuring out - the error that occurs is shown below. When I manually put the same (as saved) credentials it connects just fine. The credentials to access the gateway are the same as the credentials to access my workstation.
Any suggestions on what can disrupt "remember me" feature?

A: Try this. On the RD Gateway computer :
Change the default to be "This is a private computer"

*

*Backup C:\Windows\Web\RDWeb\Pages\en-US\Default.aspx

*Edit C:\Windows\Web\RDWeb\Pages\en-US\Default.aspx

*Find bPrivateMode = false and change the false to true
Change the setting so that the RDP credentials will only be prompted once

*

*Backup C:\Windows\Web\RDWeb\Pages\en-US\Desktops.aspx

*Edit Backup C:\Windows\Web\RDWeb\Pages\en-US\Desktops.aspx

*Find the line RDPstr += ""; and add the following line under it
RDPstr += "promptcredentialonce:i:1\n";
When you are finished the section of the file should look similar to this:
RDPstr += getUserNameProperty();
RDPstr += "";
RDPstr += "promptcredentialonce:i:1\n";

Source : RDP Gateway Customisation