grep regex how to get only results with one preceeding word?

Question: My string is :
www.abc.texas.com
mail.texas.com
subdomain.xyz.cc.texas.com
www2.texas.com

I an trying to get results only with "one" word before texas.com. Expectation when I do a regex grep :
mail.texas.com
www2.texas.com

So mail & www2 are the "one" word that I'm talking about. I tried :
grep "*.texas.com", but I get all of them in results. Can someone please help ?
Answer: You can use
grep '^[^.]*\.texas\.com'

Details:

^ - start of string
[^.]* - zero or more chars other than a . char
\.texas\.com - .texas.com string (literal . char must be escaped in the regex pattern).

See the online demo:
#!/bin/bash
s='www.abc.texas.com
mail.texas.com
subdomain.xyz.cc.texas.com
www2.texas.com'
grep '^[^.]*\.texas\.com' <<< "$s"

Output:
mail.texas.com
www2.texas.com

Answer: With awk:
awk 'BEGIN{FS=OFS="."} /texas.com$/ && NF==3' file

Output:

mail.texas.com
www2.texas.com

Set one dot as input and output field separator, check for texas.com at the end ($) of your line and check for three fields.
See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR
Answer: With your shown samples, please try following awk code.
awk -F'.' 'NF==3 && $2=="texas" && $3=="com"'  Input_file

Explanation: Simple making field separator as . for all the lines in awk program. Then in main program checking condition if NF==3(means number of fields in current line)are 3 AND 2nd field is texas and 3rd field is com if all 3 conditions are MET then print the line.


Add animated jquery fade or slide effect to backgroundimage slider

Question: I would like to change this jQuery background image script so that the images will fade-in and fade-out smooth or by sliding one in or out.
Right now the new image just pops-in what doesn't look good.
Also can't figure out how to make the images load random.
<code>(function ($) {
    var count = 0;
    var milliseconds = 4000;
    var transitionTime = 1500;
    var selector = "#target";

    setInterval(function () {
        var images = ["images/pic1.png", "images/pic2.jpg"];
        var tempImage = new Image();
        tempImage.src = images[count];

        $(tempImage).on("load", function () {
            $(selector).css("opacity", "0")
                    .animate({ opacity: 1 }, { duration: transitionTime });

            $(selector).css("background-image", "url(" + tempImage.src + ")");
        });

        if (count < images.length - 1) {
            count++;
        }
        else {
            count = 0;
        }
    }, milliseconds);
})(jQuery);
</code>
Answer: If I understand correctly you mean that you want one image fading out while next is fading in? It does look a lot smoother.
Here's a simple solution for that effect. Note that your images will have to be absolutely placed over each other.
You could make this a lot more succinct using the animation completion callback. If you used css transitions and toggleClass you could probably squeeze it into a few lines.
<code>$(document).ready( function() {
    var milliseconds = 4000;
    var transitionTime = 1500;

    var $showing, $target1, $hidden, $target2;
    $showing = $target1 = $("#selector1");
    $hidden = $target2 = $("#selector2");

    var images = ["images/pic1.png", "images/pic2.png"];
    // You could also use this instead of incrementing count.
    // Just remember not to show the same image twice in a row
    var count = Math.floor( Math.random() * images.length );

    var showImage = function(index, duration) {
        var tempImage = new Image();
        tempImage.src = images[count];

        $(tempImage).on("load", function () {
            $hidden.css("opacity", "0")
                .animate({ opacity: 1 }, { duration: duration })
                .css("background-image", "url(" + tempImage.src + ")");

            $showing.animate({ opacity: 0 }, { duration: duration });

            var $temp = $showing;
            $showing = $hidden;
            $hidden = $temp;
        });
    };

    // show the first image immediately
    showImage(count, 0);

    setInterval(function () {
        showImage(count, transitionTime);

        if (count < images.length - 1) {
            count++;
        }
        else {
            count = 0;
        }
    }, milliseconds);
});
</code>
Comment: Dear robvdv thank you for your help, I cant get it to work. I don't understand the selector1 and selector2. I want to target a single div. Could you maybe push it in a JSFiddle so I understand :D
Comment: The example works perfect only I don't know how to use it. Using wordpress I would like to target a backgroundimage of a div. changing background image with the var images in the jQuery. Then making a nice transition from one to the other images just like your example.
Comment: [edit] Ah, okay. Try this: https://jsfiddle.net/robvdv/6npy057j/2/

You should be able to point it at an arbitrary div and have it do what you want. There may be wrinkles.


Why does mongoose return object IDs' in the form of an object with an ID as a Buffer instead of string?

Question: I have a static method in my UnitSchema that finds a unit by a token. It gets passed a token as a parameter and tries to find the unit with a normal findOne method on the Unit model:
UnitSchema.statics.findByToken = async function (token) {
  const Unit = this
  let unit = await Unit.findOne({ 'Tokens.token': token }).populate('Organisation')
  return unit
}

I have had this method for a long time and it has always returned the correct object. Now, which seems like all of a sudden for no reason, it returns a "complete" mongoose object with all of the extra information and functions, and all the object ID's are now in an object format instead of a string format, such as:
ObjectID {
  _bsontype: 'ObjectID',
  id: <Buffer 5c 85 43 16 f1 ad 70 d8 f8 97 48 78>
}

instead of:
_id: '5d49595246853f14fc5168e9'

Because of this I can no longer populate fields with the normal: .populate('field') and this breaks my code.
I have searched around like crazy but can not find an explanation for this, and therefore I do not know how to fix it. Help is kindly appreciated!
Answer: I know this is a late answer. But I faced this issue recently and did some search on why the response is given in an Array of Buffer instead of an id. But I couldn't find any resource regarding it.
But, to convert the Buffer into an id. Just use String or toString().
Answer: I had the same problem before but in my case, I forgot to populate the object I'm trying to access its id.
Answer: In your example, even if the mongoose query behaved as you expected, it would still result in an express server error because you can't call JSON parser.
You must have to return the value with JSON parser.
UnitSchema.statics.findByToken = async function (token) {
  const Unit = this
  let unit = await Unit.findOne({ 'Tokens.token': token }).populate('Organisation')
  return JSON.parse(JSON.stringify(unit))
}

Comment: I'm not sure I understand, why would I need to do that? It would just return the same result? (just returning unit has been working for months as expected)
Comment: This doesn't look like the answer to the asked question. It's not clear why express was mentioned here and how json parse+stringify (performance, yeah) can help with mongoose. -1


Very slow framerate with AVFoundation and Metal in MacOS

Question: I'm trying to adapt Apple's AVCamFilter sample to MacOS. The filtering appears to work, but rendering the processed image through Metal gives me a framerate of several seconds per frame. I've tried different approaches, but have been stuck for a long time.
This is the project AVCamFilterMacOS - Can anyone with better knowledge of AVFoundation with Metal tell me what's wrong? I've been reading the documentation and practicing getting the unprocessed image to display, as well as rendering other things like models to the metal view but I can't seem to get the processed CMSampleBuffer to render at a reasonable framerate.
Even if I skip the renderer and send the videoPixelBuffer to the metal view directly, the view's performance is pretty jittery.
Here is some of the relevant rendering code I'm using in the controller:
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    processVideo(sampleBuffer: sampleBuffer)
}

func processVideo(sampleBuffer: CMSampleBuffer) {
    if !renderingEnabled {
      return
    }
guard let videoPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer),
  let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer) else {
    return
}

if !self.videoFilter.isPrepared {
  /*
   outputRetainedBufferCountHint is the number of pixel buffers the renderer retains. This value informs the renderer
   how to size its buffer pool and how many pixel buffers to preallocate. Allow 3 frames of latency to cover the dispatch_async call.
   */
  self.videoFilter.prepare(with: formatDescription, outputRetainedBufferCountHint: 3)
}

// Send the pixel buffer through the filter
guard let filteredBuffer = self.videoFilter.render(pixelBuffer: videoPixelBuffer) else {
  print("Unable to filter video buffer")
  return
}

self.previewView.pixelBuffer = filteredBuffer
}

And from the renderer:
func render(pixelBuffer: CVPixelBuffer) -> CVPixelBuffer? {
    if !isPrepared {
        assertionFailure("Invalid state: Not prepared.")
        return nil
    }

    var newPixelBuffer: CVPixelBuffer?
    CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, outputPixelBufferPool!, &newPixelBuffer)
    guard let outputPixelBuffer = newPixelBuffer else {
        print("Allocation failure: Could not get pixel buffer from pool. (\(self.description))")
        return nil
    }
    guard let inputTexture = makeTextureFromCVPixelBuffer(pixelBuffer: pixelBuffer, textureFormat: .bgra8Unorm),
        let outputTexture = makeTextureFromCVPixelBuffer(pixelBuffer: outputPixelBuffer, textureFormat: .bgra8Unorm) else {
            return nil
    }

    // Set up command queue, buffer, and encoder.
    guard let commandQueue = commandQueue,
        let commandBuffer = commandQueue.makeCommandBuffer(),
        let commandEncoder = commandBuffer.makeComputeCommandEncoder() else {
            print("Failed to create a Metal command queue.")
            CVMetalTextureCacheFlush(textureCache!, 0)
            return nil
    }

    commandEncoder.label = "Rosy Metal"
    commandEncoder.setComputePipelineState(computePipelineState!)
    commandEncoder.setTexture(inputTexture, index: 0)
    commandEncoder.setTexture(outputTexture, index: 1)

    // Set up the thread groups.
    let width = computePipelineState!.threadExecutionWidth
    let height = computePipelineState!.maxTotalThreadsPerThreadgroup / width
    let threadsPerThreadgroup = MTLSizeMake(width, height, 1)
    let threadgroupsPerGrid = MTLSize(width: (inputTexture.width + width - 1) / width,
                                      height: (inputTexture.height + height - 1) / height,
                                      depth: 1)
    commandEncoder.dispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup)

    commandEncoder.endEncoding()
    commandBuffer.commit()
    return outputPixelBuffer
}

func makeTextureFromCVPixelBuffer(pixelBuffer: CVPixelBuffer, textureFormat: MTLPixelFormat) -> MTLTexture? {
    let width = CVPixelBufferGetWidth(pixelBuffer)
    let height = CVPixelBufferGetHeight(pixelBuffer)

    // Create a Metal texture from the image buffer.
    var cvTextureOut: CVMetalTexture?
    CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, pixelBuffer, nil, textureFormat, width, height, 0, &cvTextureOut)

    guard let cvTexture = cvTextureOut, let texture = CVMetalTextureGetTexture(cvTexture) else {
        CVMetalTextureCacheFlush(textureCache, 0)

        return nil
    }

    return texture
}

And finally the metal view:
override func draw(_ rect: CGRect) {
    var pixelBuffer: CVPixelBuffer?
    var mirroring = false
    var rotation: Rotation = .rotate0Degrees

    syncQueue.sync {
        pixelBuffer = internalPixelBuffer
        mirroring = internalMirroring
        rotation = internalRotation
    }

    guard let drawable = currentDrawable,
        let currentRenderPassDescriptor = currentRenderPassDescriptor,
        let previewPixelBuffer = pixelBuffer else {
            return
    }

    // Create a Metal texture from the image buffer.
    let width = CVPixelBufferGetWidth(previewPixelBuffer)
    let height = CVPixelBufferGetHeight(previewPixelBuffer)

    if textureCache == nil {
        createTextureCache()
    }
    var cvTextureOut: CVMetalTexture?
    CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
                                              textureCache!,
                                              previewPixelBuffer,
                                              nil,
                                              .bgra8Unorm,
                                              width,
                                              height,
                                              0,
                                              &cvTextureOut)
    guard let cvTexture = cvTextureOut, let texture = CVMetalTextureGetTexture(cvTexture) else {
        print("Failed to create preview texture")

        CVMetalTextureCacheFlush(textureCache!, 0)
        return
    }

    if texture.width != textureWidth ||
        texture.height != textureHeight ||
        self.bounds != internalBounds ||
        mirroring != textureMirroring ||
        rotation != textureRotation {
        setupTransform(width: texture.width, height: texture.height, mirroring: mirroring, rotation: rotation)
    }

    // Set up command buffer and encoder
    guard let commandQueue = commandQueue else {
        print("Failed to create Metal command queue")
        CVMetalTextureCacheFlush(textureCache!, 0)
        return
    }

    guard let commandBuffer = commandQueue.makeCommandBuffer() else {
        print("Failed to create Metal command buffer")
        CVMetalTextureCacheFlush(textureCache!, 0)
        return
    }

    guard let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: currentRenderPassDescriptor) else {
        print("Failed to create Metal command encoder")
        CVMetalTextureCacheFlush(textureCache!, 0)
        return
    }

    commandEncoder.label = "Preview display"
    commandEncoder.setRenderPipelineState(renderPipelineState!)
    commandEncoder.setVertexBuffer(vertexCoordBuffer, offset: 0, index: 0)
    commandEncoder.setVertexBuffer(textCoordBuffer, offset: 0, index: 1)
    commandEncoder.setFragmentTexture(texture, index: 0)
    commandEncoder.setFragmentSamplerState(sampler, index: 0)
    commandEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
    commandEncoder.endEncoding()

    // Draw to the screen.
    commandBuffer.present(drawable)
    commandBuffer.commit()
}

All of this code is in the linked project
Answer: Capture device delegates don't own the sample buffers they receive in their callbacks, so it's incumbent on the receiver to make sure they're retained for as long as their contents are needed. This project doesn't currently ensure that.
Rather, by calling CMSampleBufferGetImageBuffer and wrapping the resulting pixel buffer in a texture, the view controller is allowing the sample buffer to be released, meaning that future operations on its corresponding pixel buffer are undefined.
One way to ensure the sample buffer lives long enough to be processed is to add a private member to the camera view controller class that retains the most-recently received sample buffer:
private var sampleBuffer: CMSampleBuffer!

and then set this member in the captureOutput(...) method before calling processVideo. You don't even have to reference it further; the fact that it's retained should prevent the stuttery and unpredictable behavior you're seeing.
This solution may not be perfect, since it retains the sample buffer for longer than strictly necessary in the event of a capture session interruption or other pause. You can devise your own scheme for managing object lifetimes; the important thing is to ensure that the root sample buffer object sticks around until you're done with any textures that refer to its contents.


Wine to install Archer T2U Plus Driver (for Windows) in Xubuntu

Question: I have an Archer T2U Plus WiFi Adapter. After purchasing I came to know that it only supports Windows and macOS and I want to run it on my Xubuntu 22.04 LTS.
I had searched regarding this thing on Stackoverflow, GitHub, AskUbuntu and various other StackExchange websites. They suggested to install various git software:
Archer-T2U-Plus-Driver on Github,
Discussion on TP-Link,
Community Discussion on AskUbuntu
But none of the above works on my Xubuntu. All of them stops on 8188au.ko installation. No matter how many times I tried that. It didn't install any driver to get this Archer WiFi adapter get running.

I was finding any workarounds and I decided to try wine to install driver.
I had used Wine Emulator on Xubuntu to install GTA Vice City game and it did install. So I downloaded the Archer T2U Plus Driver for Windows 7 (I set default Windows version to Windows 7 on wine) from its official website.
And I tried to run the Setup.exe file from the extracted folder and it keeps saying that 'Setup file cannot find the WiFi adapter'. Is it an issue with Wine or the .exe file is not compatible with wine.
Another Question is: If wine is able to install 'gta-vc-setup.exe' without any issue, then why it cannot do the same with the Adapter's setup file ?
Comment: wine is not a hardware layer so it will never work.  If you can not get it to work using the link in your 1st link buy another wifi adapter.  You did not mention the device id but it should be 2357:0120 If so https://github.com/morrownr/8821au-20210708 --works-- You just need to follow the instruction. alternatively: make a log and file a bug in the wiki on that page.
Answer: "Is it an issue with Wine or the .exe file is not compatible with wine."
Wine cannot install any kind of driver. Wine cannot control your hardware in that way.
A Windows driver won't work on a Linux kernel anyway.


How to set the time for a specific local in javascript

Question: i have a problem, and maybe someone can help me, i will explain...

i have the in javascript "var date= new date();" and its give me the local time (browser time) but i want force this data/time for a especific local... for example... Spain. i want everytime that someone enter in the page (from others country) the date need be the spanish hour.

i found some soluction but the problem is the summer time and winter time... we have offset variations because some time is +1 hours and others is +2....
someone can help me in one soluction?
thanks
email@example.com
Answer: Take a look at this article: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6016329.html
Lifted straight out from that:
 function calcTime(city, offset) {

// create Date object for current location
d = new Date();

// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);

// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));

// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();

 }

Call it like: alert(calcTime('Bombay', '+5.5')); // get Bombay time
You may need to add a bit of logic to take into account daylight saving time.
Comment: thanks, but i already checked this code, but my problem is in this case u are saying that the diference is 5hours and half... everytime, but sometime is less or more (i don't know exacly for bombay :)

how can i do this? hard code logic? for 2010? and then 2011.. bc maybe every diferent year the date that change the hour is diferent.

thanks :d
Comment: I don't know of any libraries that can work this out for you. Google returned a decent number of results for writing the logic in yourself: http://www.google.co.uk/search?q=javascript+daylight&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a


How would I make this curl request in C#?

Question: This the the curl request I need to make in C#:
curl -X PURGE http://www.example.com/image.jpg

It is the PURGE part that is throwing me off, I was going to do this in RestSharp but WebClient or whatever will work just fine as well.
Answer: I find HttpClient to be a convenient way to send requests these days. The key is to recognize that you can create a custom HttpMethod by passing a string to its constructor.
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(
    new HttpMethod("PURGE"),
    new Uri("http://www.example.com/image.jpg")))
using (var response = await client.SendAsync(request))
{
    // work with response
}


nginx serves only React HTML code in JS static build files after adding try_files directive

Question: I am building an React app image using this multi-stage build Dockerfile:
FROM node:13.12.0-alpine as build

WORKDIR /app

ENV PATH /app/node_modules/.bin:$PATH

COPY package.json ./
COPY package-lock.json ./

RUN npm config set @bit:registry https://node.bit.dev
RUN npm install --silent
RUN npm install firstname.lastname@example.com -g --silent

COPY . ./

RUN npm run build

FROM nginx
COPY --from=build /app/build /usr/share/nginx/html

and then I'm running it in a container on port 3000.
Besides this I'm also running an nginx container with the next configuration file:
server {
    listen 80 default_server;
    listen [::]:80;

    server_name _;
    server_tokens off;

    return 301 https://$host$request_uri;

}

server {
    listen 443 default_server ssl http2;
    listen [::]:443 ssl http2;

    server_name domain.com;

    ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;

    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
        proxy_pass http://xxx.xxx.xxx.xx:3000;
    }

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Now when I'm trying to access the domain the redirection seems to be working fine, but nginx seem to not serve the files correctly. In the JS static main chunk file I get only html code:

I think this must be an issue with the try_files directive because if I'm commenting that line out, I can see the first page. Also, if I'm not using nginx and open port 3000 in the firewall, the first page is again visible.
Can someone please lead me in the right direction with this configuration?
Thanks
Answer: The problem was that I wrote the try_files directive for redirecting everything to my index.html so that React can handle the routing in the nginx container running on my server and not the one built inside my React image with multi-stage build. Once I wrote the directive in the configuration file inside my React container and removed it from nginx, everything started working just fine.


How to refer to array which is inside another array?

Question: Let's imagine I have a 2d array (which basically is array of arrays). I want to have a reference to internal arrays to sort them directly or use them as arguments to some function.
type[,] array = new type[n,n]
I cannot refer to inner array with array[index] because compiler expects me to input 2 indexes.
Comment: I think what you want is a [Jagged Array (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays) instead of a Multidimensional Array.
Comment: Suggested reading: **[Multidimensional Arrays (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays)**
Answer: What you will want to use is a jagged array (arrays within an array):

A jagged array is an array whose elements are arrays, possibly of different sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.
The following is a declaration of a single-dimensional array that has
three elements, each of which is a single-dimensional array of
integers:
int[][] jaggedArray = new int[3][];

Read more here:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays
Answer: Two dimensional arrays are similar to an array of arrays, but probably the easiest way to think about them is as a grid of rows and columns. In fact, probably the most common usage is to represent a grid where the first index represents the row, and the second index represents the column of the value you're looking for, and you access items like: var item = array[row, col];
It sounds like you want to get a specific row from a two-dimensional array. One way to do this is to get the length of the second dimension (the number of columns) and then iterate through the array at a specific row value to get all the items from that row:
//                           row 0     row 1     row 2     row 3
var array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

var rowIndex = 0;
var numCols = array2D.GetLength(1);
var row0Items = new List<int>();

for (int i = 0; i < array2D.GetLength(1); i++) row0Items.Add(array2D[rowIndex, i]);

If you want to instead convert a two-dimensional array into a jagged array (which is made to be treated as an array of arrays), you could do something like:
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

int[][] jagged = new int[array2D.GetLength(0)][];

for (int row = 0; row < array2D.GetLength(0); row++)
{
    var currentRow = new List<int>();

    for (int col = 0; col < array2D.GetLength(1); col++)
    {
        currentRow.Add(array2D[row, col]);
    }

    jagged[row] = currentRow.ToArray();
}


How to change activeTintColor in TabBar (react-navigation) dynamically ?

Question: I'm using react-navigation in my app, I want to know how is possible to change activeTintColor in TabBar dynamically?
I have such code, but it doesn't change activeTintColor:
  static navigationOptions = ({ navigation, screenProps }) => ({
    actionButton: {
      title: _('create'),
      icon: 'plus',
      onPress: () => navigation.navigate('EventCreate')
    },
    tabBarLabel: _('calendar'),
    tabBarIcon: ({focused}) => <Icon featherName="calendar" active={focused}/>,
    tabBarOptions: { activeTintColor:'red'}
  })

Answer: You can do it by marking a Custom Tab Bar Component.
import { TabNavigator } from 'react-navigation';

const TabBar = TabNavigator.Presets.Default.tabBarComponent

const CustomTabBar = ({...props}) => {
    props.activeTintColor = //... change the color based on screen navigation state
    return <TabBar {...props} />
}

and use it as
const CustomTabs = TabNavigator(
    {
        // ...Screens
    },
    {
        tabBarComponent: CustomTabBar,
    },
);

The Custom Tab Bar Component has access to these props.
The navigation state objects are defined as in here


Reflection runtime performance - Java vs CLR

Question: A related post here pretty much established reflection in Java as a performance hog. Does that apply to the CLR as well? (C#, VB.NET, etc).
EDIT: How does the CLR compare to Java when it comes to reflection? Was that ever benchmarked?
Answer: I wouldn't really care about the instantiation performance of the object using reflection itself but the actual performance of methods and such since those are after all what I'll be using from the class anyway.
Surely the instantiation takes a lot of time as can be seen in the linked post but since you're most likely using the object's methods instead of just instantiating it, you shouldn't worry too much about reflection performance - as long as you're not doing the method calls by invoking reflected Method objects!
Besides you only need one reflected instance of the object, use .clone() and other clever tricks if you need to create more copies.
Comment: What if you are using reflection as part of your logic - not necessarily instantiating anything but using your type definition as a guide - sort of "meta-programming" ?
Comment: If you're not instantiating objects, why would you want to reflect (parts of) them anyway? I'd be interested to see an example of what you exactly mean though, if you have time please explain in more detail.
Comment: Suppose you have a list of objects and want to edit their values. Through reflection you could build a single user interface that would allow you to do that. You can define attributes for the labels, max size, etc.
Comment: Ah, valid case of such behavior and now I understand what you mean. Yeah, that's unfortunately slow but if I remember correctly (a bit hazy here) it is possible to create a proxy object using java.lang.reflect.Proxy for speeding up such functionality by reusing the proxy for every object in list.
Comment: I understand that in Java it is slow, but I'm curious if the same applies to C#.
Answer: Yeah, reflection in .NET is a performance intensive operation too as it requires querying metadata tables in assemblies.
Comment: Is that still true even after the assemblies are loaded in memory?
Comment: Yes. Dynamically resolving types and members by name requires looking them up in the type system which is clearly slower than static resolution.
Comment: Yes it is, because even though the assemblies are in memory you must still look at the metadata tables which is the slow part.
Comment: Also... how does the CLR compare to Java when it comes to reflection?
Comment: It's very easy to see it's MUCH slower by a simple code snippet. Similar to the one you linked for Java. However it's really a runtime dependent thing. You should benchmark against a specific version of Java runtime and .NET runtime.
Answer: The default implementation of Equals for value types is implemented using Reflection. It works, but it is darn slow and it is easy to implement a specific version, which is much faster (the catch is that you have to implement GetHashCode as well). How much faster depends on the actual value type of course, but I have seen some huge boosts here.


Static outbound IP for Azure Web Apps

Question: Is there a 'quick and dirty' way of funnelling calls to a web service via a certain IP address?  Possibly in code (C#)?
I'm working on this Azure website (PaaS no VM) that's got it's own domain secured by SSL.
e.g. myapp.azurewebsites.net -> https://myapp.com
The system is using a 3rd party web service that uses whitelisted IPs for access control.  Unfortunately they are not happy whitelisting the standard Azure egress IPs.
So what I need to do is find a way to call that web service via our own IP address (the one that came with the domain name package).
If possible, only that traffic, not all outgoing.
I've come across several solutions but I'd rather not want to compromise the stability of the production website by experimenting with App Service Environment.
Answer: I think the scenario being asked about is outbound calls from an app running on Azure App Service (aka Azure Websites), to an external endpoint.
In that scenario, the outbound calls from the web app are NAT'd using a pool of IP addresses allocated for the App Service scale unit that is running your app.
Using the "preview" portal (portal.azure.com), drill into the website blade for your app and click through "All settings" --> "Properties".  In the properties blade that appears, there is a textbox called "OUTBOUND IP ADDRESSES".  Those are the values you need to give to the third party provider to whitelist.
Comment: I'm aware of said pool of IPs. The third party vendor is not keen on whitelisting IPs that aren't exclusive to the system.
Comment: So has anyone found a solution to this? I assume there's no way to get a static outbound IP address that's unique to an App Service? Are folks using VMs for anything that requires a trusted IP?
Comment: Therein lies the problem!

Static outbound IP for Azure Web Apps


Building Flutter Engine on Ubuntu

Question: I use Ubuntu 20.04. When I run https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment step 7
<code> sudo ./build/install-build-deps-android.sh
ERROR: Only Ubuntu 12.04 (precise), 14.04 (trusty),  14.10 (utopic), 15.04 (vivid), 16.04 (xenial), 18.04 (bionic),  and Debian (rodete and stretch) are currently supported
</code>
And the doc says:
<code>If you're on Linux, run the following. Note: These scripts are distro- and version-specific, so are not guaranteed to work on every configuration. If they fail, you may need to find comparable packages to the ones that weren't found.
</code>
Based on the documentation, How do I know which packages are not compatible.
Answer: Maybe you can modify that install-build-deps-android.sh script and force 20.04 and try to go on the building process?
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead).

Building Flutter Engine on Ubuntu


how to filter a string without using any additional data structures(no additional strs, lists etc.) nor any string methods?

Question: I am trying to make a function that checks whether or not a string is a palindrome. It should only consider alphanumeric chars, including no spaces. I basically have to code whats below without any methods on the string (so no isalnum(), lower() etc.), nor adding additional data structures(so without the y/' '). I cant think of a way to achieve this. Is it possible? The function should consider uppercase chars equal to their lower case counter partts
def isPalindrome_py(x):
    y = ''
    for i in range(len(x)):
        if x[i] == ' ':
            pass
        elif x[i].isalnum():
            y += x[i]
    y = y.lower()
    if y[::-1] == y:
        return True
    else:
        return False

edit:
as an example - isPalindrome_py("#RaCe CaR$!") should return True
Comment: Why cannot use any string method - like `isalnum()` - that's Python built-ins?
Comment: This is the constraint
Answer: def isPal(x):
    if len(x) < 2:
        return True
    elif not ('0' <= x[0] <= '9' or 'A' <= x[0] <= 'Z' or 'a' <= x[0] <= 'z'):
        return isPal(x[1:])
    elif not ('0' <= x[-1] <= '9' or 'A' <= x[-1] <= 'Z' or 'a' <= x[-1] <= 'z'):
        return isPal(x[:-1])
    elif x[0] != x[-1] and x[0] >= 'A' and x[-1] >= 'A' and ord(x[0]) + 32 != ord(x[-1]) and ord(x[0]) - 32 != ord(x[-1]):
        return False
    else:
        return isPal(x[1:-1])

Now let's unpack this monster
This function works by trying to find characters that would imply that the string is not a palindrome, and if it can't find any violations, concluding that the string must be a palindrome.
The first clause checks if the string is trivially a palindrome (since single characters and the empty string are all palindromes)
The second clause (elif not ('0' <= x[0]...) checks if the first character in the string is alphanumeric. If it isn't it's disregarded.
The third clause does the same but for the last character in the string.
The fourth clause checks whether the first character in the string is the same as the last character in the string. It makes use of the fact that uppercase and lowercase letters are 32 removed from each other in ASCII.


What is a safe length of JavaScript strings?

Question: Considering charAt(), charCodeAt(), and codePointAt() I find a discrepancy between what the parameter means.  Before I really thought about it I thought you would always be safe to access the character at length-1.  But I read the difference between charCodeAt() and codePointAt() is that charCodeAt() refers to 16-bit (byte pairs) so besides reading i you would also need i+1 if they were surrogate pairs (as is the methodology with UTF-16).  Whereas codePointAt() needs a parameter that references the UTF-8 character position (zero based).  So now I'm in a quandary as to whether length counts the number of characters, or the number of byte pairs UTF-16 style.  I believe JavaScript holds strings as UTF-16, but using length-1 from that on a string that had lots of 4-byte characters with the codePointAt() function would be off the end of the string!!
Comment: Strings can be any length, so long as there is enough memory.
Answer: The length of strings is counted in 16-bit unsigned integer values ("elements") or code units (which together form a valid or invalid UTF16 code unit sequence), and so are its indices. We might also call them "characters".
It doesn't matter whether you access them as properties or via charAt, chatCodeAt and codePointAt, length - 1 will always be a valid index. A code point might however be encoded as a surrogate pair spanning two indices. There is no builtin method to measure the number of these, but the default string iterator will yield them so you can count them using a for … of loop.
Comment: Please propose a solution for the OP's question "what is the safe length".
Comment: Thanks for your answer.  Very disappointed though that JavaScript is so useless that it can provide an illegal return value if you happen to give it an index for the second of surrogate pairs.
Comment: @Clive What do you mean by "illegal"? It's just the code unit at that index, irregardless of what bytes might be in front of it. But yes, JavaScript strings are immutable `Uint16Array`s instead of Unicode character lists.
Comment: @Bergi  I called it illegal because of the substring 'char' in all 3 of these functions' names.  By their names they purport to give the code of the 'character', not the code of the _16-bit unsigned integer values_.
Comment: @Bergi.   "irregardless" - wow, is that a Bushism?   (like "misunderestimated")  hehe
Answer: Use [...str].length for the count of character.

var mb = "";
console.log(mb.length);
console.log([...mb].length); // "real" length (ES6)
console.log(mb.charAt(0)); // The first two byte
console.log(mb.codePointAt(0)); // The first two byte
console.log(mb.codePointAt(1)); // The second two byte
console.log(mb.charCodeAt(0)); // The four bytes combined (ES6)
console.log(mb.charCodeAt(1)); // The second two byte (ES6)
Comment: I'm presuming your mb character as set is a non-basic multiligual plane character.  Thank you for your answer and the included source.  But I am disillusioned about JavaScript's `length` property, it seems to not state how many characters there are at all.  I didn't know about the elipses.
Comment: I recommend to use `Array.from(…)` for casting iterables to arrays, spread syntax should only be used as part of literals.


Covering space covers simply connected set correctly

Question: I found this proposition in a paper stated as a well known result from topology, but I can neither find this result in my textbooks nor proof it by myself:
Let $p:E \rightarrow B$ be a covering space of degree $d$ and $A \subset B$ a simply connected subset. Then $p^{-1}(A)=U_1 \cup\dots\cup U_d$ decomposes into $d$ disjoint path-connected subsets, such that $p|_{U_i}:U_i\rightarrow A$ is a homeomorphism.
Can anybody help?
Comment: What are the coverings of a simply connected space?
Comment: This is false in general. You need to assume that $A$ is locally path connected.
Answer: It is not difficult, depending on the tools you want to use.
First, note that the restriction $p:p^{-1}(A)\to A$ is a covering. Now, let $C$ be a connected component of $p^{-1}(A)$. Then the restriction of $p$ to $C$
$$p|_C:C\to A$$ is a covering. Since $A$ is simply connected, that covering must be the universal covering, whence a homeomorphism.
What we are proved so far is that $p^{-1}(A)$ consists of some number $n$ of connected components such that the restriction of $p$ to any such component is a homeomorphism. Since you know that the degree is $d$, you know now that $n=d$.
Comment: This is not true. For example, the Warsaw circle is simply connected and has connected covering spaces of any degree which have no decomposition as required. See https://math.stackexchange.com/q/3063530. You need the additional assumption that $A$  is *locally path connected*.
Comment: Yes you're right: I always make assumption on spaces to bee "good" (connected, locally path connected and locally semi-locally simply connected) when I read "simply connected"; but you're right: this is not maybe the usual setting. For connected, with trivial fundamental group, but not locally path connected, one can have connected coverings with trivial fundamental groups which are not homeomorphisms. Like the closed topological sinusoid (is that the Warsaw circle?).
Comment: I d not know what the closed topological sinusoid is (probably the  [closed topologist's sine curve](https://en.wikipedia.org/wiki/Topologist%27s_sine_curve) aka Warsaw sine curve). The Warsaw circle $W$ is [this space](https://de.wikipedia.org/wiki/Datei:Warsaw_Circle.png). You can embed $W$ into a plane annulus which is certainly "good" and has a $d$-sheeted covering for all $d \in \mathbb N \cup \{\infty\}$.  This restricts to a $d$-sheeted covering of $W$. But although $W$ is simply connected,  this covering is not equivalent to $W \times F$.


swipe tab vs scroll tab android

Question: I need to use tabs on my app ,
I may need 4 to 7 tabs on my fragmentActivity .
I heard swipe tabs are best suited for displaying 3 or fewer tabs . I've already use them in another app but the number of tabs was 3 . I don't know if it's true or not but they worked perfect on that app .
I need to make something like Google Play Store app , as you can see there are lots of tabs , what are those tabs ?
I don't need to have any communication between these tabs .
What is the best tab to use when I have 4 to 7 tabs ?
I need to run the app on older devices like 2.3+
thanks you
Answer: Google Play store app uses Scrolling Tabs. Here's an example:
MainActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends ActionBarActivity {
    // used ActionBarActivity from v7 support library,
    // for backward compatibility

    private ViewPager viewPager;
    private MyPagerAdapter adapter;

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

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        adapter = new MyPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(adapter);
    }

    private static class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            // each page corresponds to a new fragment
            // I'll return the same fragment for now
            return new MyFragment();
        }

        @Override
        public int getCount() {
            // return no of pages
            return 5;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // return the page title
            return "Tab " + position;
        }
    }

    public static class MyFragment extends Fragment {
        public MyFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }
}

activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="MergeRootFrame" >

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <android.support.v4.view.PagerTitleStrip
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#33b5e5"
            android:paddingBottom="4dp"
            android:paddingTop="4dp"
            android:textColor="#fff" />
    </android.support.v4.view.ViewPager>

</FrameLayout>

fragment_main.xml is just the hello world fragment. You will need to customize the PagerTitleStrip to make it look like a tab. For that I really love this library.
Hope this helps :)
Answer: It is better to use scroll tabs in your case.
Use fragment class from support.v4.app lib,this will  enable you to use scroll tabs with devices older than API level 11.
For using  support lib,include it in dependencies in builf.gradle file.
Also extend adapter with FragmentStatePagerAdapter instead of FragmentPagerAdapter to store the instance before it getting destroyed.
Here is an example code snippet
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends FragmentActivity {

ViewPager pager = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    pager = (ViewPager) findViewById(R.id.pager);
    android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
    pager.setAdapter(new MyAdapter(manager));

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public class MyAdapter extends FragmentStatePagerAdapter{

    public MyAdapter(android.support.v4.app.FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment frag = null;
        if(i==0){
            frag = new FragmentA();
        }
        if(i==1){
            frag = new FragmentB();
        }
        if(i==2){
            frag = new FragmentC();
        }
        return frag;
    }

    @Override
    public int getCount() {
        return 3;
    }
    public CharSequence getPageTitle(int i){
        String title = new String();
        if(i==0){
           title = "FRAG1";
        }
        if(i==1){
            title = "FRAG2";
        }
        if(i==2){
            title = "FRAG3";
        }
        return title;
    }
}

}

swipe tab vs scroll tab android


Any way to recover lost items?

Question: I kinda accidentally discarded an incense while searching for Pokemon. Is there any way I can recover my incense without having to pay, or is it lost for good?
Answer: Once you discard an item there is no way to get it back.

Any way to recover lost items?


Installation warning or fail

Question: When i want to install nvidia-355 i get;
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
nvidia-355 : Depends: xorg-video-abi-11 but it is not installable or
                   xorg-video-abi-12 but it is not installable or
                   xorg-video-abi-13 but it is not installable or
                   xorg-video-abi-14 but it is not installable or
                   xorg-video-abi-15 but it is not installable or
                   xorg-video-abi-18 but it is not installable or
                   xorg-video-abi-19 but it is not installable
          Recommends: libcuda1-355 but it is not going to be installed
          Recommends: nvidia-opencl-icd-355 but it is not going to be installed
N: Ignoring file '50unattended-upgrades.ucf-old' in directory '/etc/apt/apt.conf.d/' as it has an invalid filename extension
E: Unable to correct problems, you have held broken packages.

Whenever i want to update or install something i always get
N: Ignoring file '50unattended-upgrades.ucf-old' in directory '/etc/apt/apt.conf.d/' as it has an invalid filename extension

any ideas to solve that?
Answer: Since whichever of apt, apt-get or other you used successfully Ignored the file, one can infer that it did not Use the file.
Therefore, you can move it elsewhere for examination:
sudo mv --target-directory=/tmp /etc/apt/apt.conf.d/50unattended-upgrades.ucf-old

Or, simply delete it:
sudo rm /etc/apt/apt.conf.d/50unattended-upgrades.ucf-old

Installation warning or fail


signing using Generated RSA KeyPair Bouncy Castle


How do I return all the values of only one of the table columns through a GET?

Question: I have an API created with Loopback4, connected to a database and a table in mySQL.
Below is the structure of my table:

I want to write a function to create a @GET method to return all the userID (exclude the other fields).
Values returned are in JSON format, expected results are as below:
{
    "userID": 2192
},
{
    "userID":1198
},
{
    "userID":5555
}

Answer: You can create a FilterBuilder to include a particular attribute. Here is a related docs page: https://loopback.io/doc/en/lb4/Querying-data.html.
It will be something like below for the controller method:
let filterBuilder = new FilterBuilder(filter);
filterBuilder.fields('userID');
return this.testRepository.find(filterBuilder.filter);

Comment: Thank you! This seems like a simple solution, however as the userID column has duplicate userIDs, how can I have the response prevent this?
Answer: You can try the following way to fetch the result of query in the form of array and then get column wise result on the basis of index.
Query query = em.createQuery("SELECT u.id, u.userId, u.name, u.price FROM UserDetails u");
List<Object[]> rows = query.getResultList();
//This will give you the result of each column in array format
//userId will be at index 1


Equivalence Between Law of Excluded Middle and Self-Implication

Question: We know that $P \to Q$ is equivalent to $\neg P \lor Q$, as can be verified easily in truth table. Now suppose we have proof for self-implication below
[the axiom system is Lukasiewicz's, with L1: $P \to (Q \to P)$, L2: $(P \to (Q \to R) \to ((P \to Q) \to (P \to R))$]:
(1) $P \to ((P \to P) \to P)$ --- (L1)
(2) $(P \to ((P \to P) \to P)) \to ((P \to (P \to P)) \to (P \to P))$ --- (L2)
(3) $(P \to (P \to P)) \to (P \to P)$ --- (1,2 MP)
(4) $P \to (P \to P)$ --- (L1)
(5) $P \to P$ --- (3,4 MP)
This proof establishes that $P \to P$. It is at this point that I realized two things:
First, since we know that $P \to P$ is equivalent to $\neg P \lor P$ and since $\neg P \lor P$ is the Law of Excluded Middle (or more precisely $P \lor \neg P$, but the order of negation don't matter), can it be said that the two are the same? That is, LEM is self-implication. If so, then a logic without LEM (intuitionistic logic) is a logic without self-implication. In other words, in a logic where LEM is not a theorem, self-implication is also not a theorem. Is my reasoning correct?
Second, as a corrolary of the first, can we concludes that the above proof is also (albeit in a disguised form, given semantic reading of equivalence between propositions) proof of LEM?
Comment: I am not an expert on intuitionist logic, but the [Wikipedia page](https://en.wikipedia.org/wiki/Intuitionistic_logic) seems to indicate that the two axioms you are using to derive $P \to P$ are axioms of intuitionist logic as well. So, $P \to P$ would seem to be a theorem of intuitionist logic. And if $P \lor \neg P$ is not, then the equivalence of $P \to P$ and $P \lor \neg P$ must be something that does not hold for intuitionist logic.
Answer: Self-implication is true in intuitionistic logic as well. It really should be: if we assume $P$, we really should be able to derive $P$.
The point is that $P \to Q$ and $\neg P \lor Q$ are not equivalent in intuitionistic logic.  The direction: $P \to Q$ implies $\neg P \lor Q$ uses LEM (and cannot be proved without LEM).
As pointed out in the comments, it may be worth noting that truth tables do not work for intuitionistic logic. That is, if a truth table says two formulas are equivalent, then they are classically equivalent, but not necessarily intuitionistically equivalent. There are similar semantics for intuitionistic logic, called Heyting algebras, but this is more complicated.
Comment: As a bonus, another way of defining $P\to Q$ in classical logic is $\neg(P\land\neg Q)$. In intuitionistic logic, we end up with $\neg P\lor Q\implies P\to Q\implies\neg(P\land\neg Q)$ but neither of the reverse entailments.
Comment: I'd recommend mentioning that truth tables is a semantics for classical propositional logic, and as such is not complete for intuitionistic propositional logic, i.e. that something is a classical tautology doesn't mean it's provable/valid intuitionistically. Different semantics are required for intuitionistic logic.
Comment: @Derek I avoided semantics on purpose, because I do not know what OP is familiar with and it might just cause confusion.
Comment: The OP references truth tables. Stating that truth tables already presuppose classical logic and therefore don't "work" for intuitionistic logic seems reasonable. My previous comment is more technical than I'd recommend formulating it in the answer because it was directed at you rather than the OP. Nevertheless, the source of the OP's confusion was an equivalence justified by truth tables, so it seems important to directly address that. In my experience, an incorrect belief along the lines that truth tables are the final arbiter of any logical question seems very common.
Comment: @Derek Ah, I see. I added a bit about truth tables. Thank you for the suggestion.


Why did this script go insane?

Question: Aw man!
This is a VBScript that was supposed to change all the files in the directory that are named like
1229_002510 to 2010-12-29_002510
What ended up happening is the script never terminated.
After one pass through the file names, it KEPT GOING and prepended 2010- MULTIPLE TIMES until I killed the script.
The bug only appears if you launch the script through CScript at cmd.
(Launch with:  cscript "filename.vbs")
So now I have a folderful of files like
2010-20-10-20-10-20-10-20-10-20-10-20-10-20-10-20-10-20-10-20-10-11-26_023335
Realize I'm a VBScript noob.
The script appears to work in test mode (just printing file names) but as soon as you have it work on actual files, it does exhibit the described behavior.
' shell script that changes dates like
' 1219_005530 to 2010-12-19_005530

' create a root filesystemobject:
Dim ofso
Set ofso = CreateObject( "Scripting.FileSystemObject" )

' create a folder object USING that root filesystem object
Dim folder

' that's the current directory
Set folder = ofso.GetFolder( "." )

' now, visit each file in the folder
Dim fileo
For Each fileo In folder.Files

  dim originalName
  originalName = CStr( fileo.Name )

  ' cut first 2 chars, prepend 2010-, re-add first 2 chars + "-"
  dim monthNumber
  monthNumber = Mid( originalName, 1, 2 )

  ' don't change the source file!
  If Right( originalName, 3 ) = "vbs" Then
    WSH.echo( "Not changing " & originalName )
  Else
    dim newName
    newName = "2010-" & monthNumber & "-" & Mid( originalName, 3 )

    WSH.echo( originalName )
    WSH.echo( newName & " < CHANGED TO" )

    ' ONLY ENABLE THIS LINE ONCE DEBUGGING COMPLETE
    'fileo.Name = newName
  End If

  Next

' PAUSE BEFORE EXIT

Comment: Since you're using FileSystemObject: `ofso.GetExtensionName(originalName)` will do the same as `Right( originalName, 3 )` and is more readable -- and works for extensions made of <> 3 chars.
Answer: I dont know what you dit, but i copy/pasted your script and it works just as you intended. (Windows 7)
Edit: Try to set a max on the times the script may go tru the loop. That will fix it. Might be that the script sees the renamed files as new files, thus creating an infinite loop.
Comment: Ah but, did you try it on actual files?  Catch is, the bug only appears once you try it on actual files
Comment: i did :-) just 1 file tho. IMG_20101231_212421.jpg to 2010-IM-G_20101231_212421.jpg
Comment: Ah wait.  It only happens if you run this through `CScript`
Comment: Ok.  Well the folder I tried it on had 191 objects totalling 4.62 GB.
Answer: You can perform this task in 2 steps. First scan a directory for files and collect their names into array, and then run through this array and rename files. This should be more reliable.
And consider to switch to JScript. VBS is just ugly compared to it.
Comment: Yeah, but its kind of surprising that WSH has this really weird behaviour
Comment: I think it's because renaming a file resets folder iterator or adds renamed file to it, so it never ends. This also may depend on Windows and WSH version

Why did this script go insane?


My website is not shown up in google search http://www.refillwallet.com

Question: It's strange for me, I have a website.
Which is live from more than 4 months. But still if i search for the domain "refillwallet" on google search. I don't see my website in search results. Where else same this is working in Bing search and Yahoo search perfectly fine.
Please help me rectifying this issue.
Thanks in advance.
Comment: research how to do search engine optimization. this is a good place to start https://moz.com/beginners-guide-to-seo
Comment: this is not related to programming. You can contact google support for why their crawlers are not able to get your site. There is a detailed procedure to address such issues.
Comment: search on how to add website to google search engine.
Comment: I'm voting to close this question as off-topic because it is about SEO instead of directly about programming.
Answer: Check your robots.txt file, it might work against Google and another option is to add it manually to search console.
Edit
Its currently on Google.


How to add a static content to Bootstrap carousel?

Question: Here I have code for Bootstarp carousel and it is working fine for all the different devices.

Image 1

Image 1 Description

Image 1

Image 1 Description

Image 1

Image 1 Description

Now, my doubt is that, How can I add some content like buttons(Login, Register) which is common on all slides to the carousel? And it is always be the centre to the slide image and it should be responsive as well.
Code of the buttons is shown below. And this what appears on all the slides as static.

          LOGIN
          REGISTER

I have tried in different ways, and it working fine for large devices but not for the small devices and due to these buttons, in mobile devices right nav button of the carousel is not working.
Any help is appreciated. Thanks in advance.
Comment: place them in a div with fixed position?
Comment: Even though I placed them in a div with fixed position there is no change at all!
Comment: Did you try adding it to the carousel caption div?
Comment: If I give css to carousel caption, I have to place static content on every slide. am I right? @ArshadMuhammed
Comment: Yes. You don't want to do that?
Comment: If you have a navbar you can add these buttons to that. : justasuggestion
Answer: Try this on your style
 position :Static; top: %; right: %;
 for button class
Reference for positioning:http://www.w3schools.com/css/css_positioning.asp


Line With Two Origins Quotient

Question: I am a bit confused with the following wording in the "line with two origins" problem (from Lee's Smooth Manifolds):

Let X be the set of points $(x,y)\in \mathbb{R}^2$ such that $y = \pm 1$, and let $M$ be the quotient of $X$ by the equivalence relation generated by $(x,-1)\sim (x, 1)$ for all $x \neq 0$.

In particular, if $q: (x, y) \to \{(x, 1), (x, -1)\}, y=\pm 1, x \neq 0$ is the quotient map, I thought a set $G \subset M$ was open if and only if $q^{-1}(G)\subset X$ were open. Is $X$ a subspace of $\mathbb{R}^2$? Clarification with regard to the quotient map definition would be much appreciated.
Comment: Editing a question after a good answer is not only unnecessary, but it is a particularly bad idea when the edits obscure important points that are addressed in the answer, thus invalidating portions of the answer and confusing future readers who come to this post to understand the topic. I suggest that you should simply roll back those edits.
Answer: A couple of points, one of which might clear it up for you:

Your definition of the quotient map is almost correct, but the condition is that $g^{-1}(G)$ should be open in $X$, not in $\mathbb{R}^2$. The set $X$ is to be regarded as a subspace of $\mathbb{R}^2$ with the subspace topology.
$X$ is then homeomorphic to the disjoint union of two real lines.
The line with two origins is not homeomorphic to $\mathbb{R}$ as you seem to say (but I may have misunderstood you there). If you consider an open interval of the line with two origins which doesn't contain either origin, then such an open interval will be homeomorphic to an open interval on the real line.

Edit: and as Thomas points out, your definition of the quotient map is valid for $x\neq 0$ but not at zero.
Comment: @LukeTux for all points except the origin, yes. For $x=0$ we get two seperate classes $\{ (0,1) \}$ and $\{ (0,-1) \}$.
Comment: Thank you. As a follow up: is an element of the quotient space a set consisting of two points?

Line With Two Origins Quotient


To split only Chinese characters in java

Question: I am writing a java application; but stuck on this point.
Basically I have a string of Chinese characters with ALSO some possible Latin chars or numbers, lets say:
查詢促進民間參與公共建設法(210BOT法).

I want to split those Chinese chars except the Latin or numbers as "BOT" above. So, at the end I will have this kind of list:
[ 查, 詢, 促, 進, 民, 間, 參, 與, 公, 共, 建, 設, 法, (, 210, BOT, 法, ), ., ]
How can I resolve this problem (for java)?
Answer: Chinese characters lies within certain Unicode ranges:

2F00-2FDF: Kangxi
4E00-9FAF: CJK
3400-4DBF: CJK Extension

So all you basically need to do is to check if the character's codepoint lies within the known ranges. This example is a good starting point to write a stackbased parser/splitter, you only need to extend it to separate digits from latin letters, which should be obvious enough (hint: Character#isDigit()):
Set<UnicodeBlock> chineseUnicodeBlocks = new HashSet<UnicodeBlock>() {{
    add(UnicodeBlock.CJK_COMPATIBILITY);
    add(UnicodeBlock.CJK_COMPATIBILITY_FORMS);
    add(UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS);
    add(UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT);
    add(UnicodeBlock.CJK_RADICALS_SUPPLEMENT);
    add(UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION);
    add(UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS);
    add(UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A);
    add(UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B);
    add(UnicodeBlock.KANGXI_RADICALS);
    add(UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS);
}};

String mixedChinese = "查詢促進民間參與公共建設法(210BOT法)";

for (char c : mixedChinese.toCharArray()) {
    if (chineseUnicodeBlocks.contains(UnicodeBlock.of(c))) {
        System.out.println(c + " is chinese");
    } else {
        System.out.println(c + " is not chinese");
    }
}

Good luck.
Comment: As an extension, I believe a character class in an regexp. spanning the above unicode ranges would also work.
Comment: Not really if you also want to intercept on groups of digits/letters/hyphens/whateverlatin. A stackbased parser is a better tool for this kind of job.
Comment: @MichieldeMare Just substitute the unicode blocks in answer where necessary.
Answer: Diclaimer: I'm a complete Lucene newbie.
Using the latest version of Lucene (3.6.0 at the time of writing) I manage to get close to the result you require.
  Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36, Collections.emptySet());

  List<String> words = new ArrayList<String>();
  TokenStream tokenStream = analyzer.tokenStream("content", new StringReader(original));
  CharTermAttribute termAttribute = tokenStream.addAttribute(CharTermAttribute.class);

  try {
    tokenStream.reset(); // Resets this stream to the beginning. (Required)
    while (tokenStream.incrementToken()) {
      words.add(termAttribute.toString());
    }
    tokenStream.end(); // Perform end-of-stream operations, e.g. set the final offset.
  }
  finally {
    tokenStream.close(); // Release resources associated with this stream.
  }

The result I get is:
[查, 詢, 促, 進, 民, 間, 參, 與, 公, 共, 建, 設, 法, 210bot, 法]

Answer: Here's an approach I would take.
You can use Character.codePointAt(char[] charArray, int index) to return the Unicode value for a char in your char array.
You will also need a mapping of Latin Unicode characters.
If you look in the source of Character.UnicodeBlock, the full LATIN block is the interval [0x0000, 0x0249]. So basically you check if your Unicode code point is somewhere within that interval.
I suspect there is a way to just use a Character.Subset to check if it contains your char, but I haven't looked into that.


Pandas - find specific value in entire dataframe

Question: I have a dataframe and I want to search all columns for values that is text 'Apple'. I know how to do it with one column, but how can I apply this to ALL columns? I want to make it a function, so that next time I can directly use it to search for other values in other dateframes.
Thanks.
Comment: `(df=='Apple').sum()`
This will give the number of rows in all columns where the value = 'Apple
Comment: Possible duplicate of https://stackoverflow.com/questions/26640129/search-for-string-in-all-pandas-dataframe-columns-and-filter
Answer: You can try searching entire dataframe using the below code:
df[df.eq("Apple").any(1)]
# if using pandas version >=1.5, passing positional argument was deprecated
df[df.eq("Apple").any(axis=1)]

Using numpy comparison
df[(df.values.ravel() == "Apple").reshape(df.shape).any(1)]

Timing (pandas version 1.5.2):
While the .ravel() approach is initially quicker on smaller datasets, using .eq() is faster on larger datasets.
small_df = pd.DataFrame({"A":list(range(500)), "B":list(range(500, 1000))})
large_df = pd.DataFrame({"A":list(range(100000)), "B":list(range(100000, 200000))})
largest_df = pd.DataFrame({"A":list(range(1000000)), "B":list(range(1000000, 2000000))})

def filter_df_by_value_eq(df, value):
    return df[df.eq(value).any(axis=1)]

def filter_df_by_value_ravel(df, value):
    return df[(df.values.ravel() == value).reshape(df.shape).any(1)]

In [8]: %timeit filter_df_by_value_eq(small_df, 612)
175 µs ± 1.01 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [9]: %timeit filter_df_by_value_ravel(small_df, 612)
78.9 µs ± 215 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [10]: %timeit filter_df_by_value_eq(large_df, 1502964)
307 µs ± 2.21 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

In [11]: %timeit filter_df_by_value_ravel(large_df, 1502964)
1.56 ms ± 13.2 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

In [12]: %timeit filter_df_by_value_eq(largest_df, 10502964)
3.04 ms ± 66.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [13]: %timeit filter_df_by_value_ravel(largest_df, 10502964)
15.2 ms ± 43.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Answer: Something like this:
In [1188]: df
Out[1188]:
   id   name      n1
0   1   Zeke     may
1   2  Apple    maya
2   3      a   Apple
3   4   Maya       a
4   5  Derek  Mayank
5   6     an      is
6   7    the     the

Just have a check like:
In [1190]: df[df == 'Apple']
Out[1190]:
   id   name     n1
0 NaN    NaN    NaN
1 NaN  Apple    NaN
2 NaN    NaN  Apple
3 NaN    NaN    NaN
4 NaN    NaN    NaN
5 NaN    NaN    NaN
6 NaN    NaN    NaN

OR
In [1191]: df.where(df == 'Apple')
Out[1191]:
   id   name     n1
0 NaN    NaN    NaN
1 NaN  Apple    NaN
2 NaN    NaN  Apple
3 NaN    NaN    NaN
4 NaN    NaN    NaN
5 NaN    NaN    NaN
6 NaN    NaN    NaN

This lets you search through all the columns of a dataframe.
Answer: import pandas library
import pandas as pd

Raw Data or URL of file
raw_data = {'first_name': ['Mihir', 'Mihir', 'Raju', 'Johan', 'Johan'],
               'last_name': ['Patel', 'Patel', 'Ali', 'Khan', 'Khan'],
               'age': [42, 42, 36, 24, 53]}
df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age'])

Find The Value
df.loc[df['first_name']=='Mihir']

Comment: This finds the value from a single column. The OP specifically asked for a solution that searched the entire df.
Answer: Search list of values in given dataframe all columns:
filter_data = df[df.isin(['Apple', 'Green Apple']).any(1)]

Search single value in given dataframe all columns:
filter_data = df[df.contains('Apple').any(1)]

Comment: Are you refering to https://pandas.pydata.org/docs/reference/api/pandas.Series.str.contains.html ?  Because dataframe does not have any "contains" method
Comment: What does `any(n)` do?
Comment: no .contains method.  Tito was correct.
Comment: The `isin()` is quite quick. But the `.contains()` only works on a single column and needs to be prefixed by the column name and `.str` e.g. `df.name.str.contains()`
Answer: Take what you have for your single method and include in the for loop.
for column in df:
    #your code here


Do calves jump?

Question: This may seem like an odd question, but yes, this is what I wanted to know: do the baby cows jump occasionally, without specific reason?
Rationale:
I've built an automatic cow butchery. I have a manual "mercy switch" that lets me save baby cows and return them to the herd - but I failed to use it once, and a baby cow fell into the "lava blade" trap. And... it fit in the 1-block area right under the lava blade, on top of the hoppers. That means, it would get butchered and drop fried steaks as soon as it matures - if it lives that long. Although, the only way it can die now before reaching adulthood is by jumping up, into the lava. I'd have to sit and observe it for nearly 20 minutes to be sure that doesn't happen (and then I still wouldn't be sure if it wasn't just a non-jumpy calf). If they don't jump, I could just scratch the mercy switch and its ramp, and just let the calves await the cruel death coming with adulthood.
(and for a fact, I know adult pigs do jump without good reason. One of them blundered onto my farmland and kept jumping in place until a block converted to soil.)
Comment: This is Arqade. "Odd questions" is what we're known for.
Comment: Farmland is not exactly "no reason", as it is not a complete block, and that's at least a possible reason to glitch. Calves do jump to navigate terrain, but I do not believe I've seen any mob jump near a 2-meter wall it has no chance of climbing.
Comment: @OrcJMR I'm pretty sure I've seen zombies do that, but that was a while ago and it may have been fixed in an update.
Comment: If you let them go through they'll just fill up the blade area and prevent adults from being "processed", backing up your whole grinder. Keep your mercy switch, or add a tunnel past the blade that calves can wander off down for "rehabilitation."
Comment: @OrcJMR: Today a horse standing on the sand (the desert) started to continuously jump in place, and there were no half-blocks or anything like that around. I guess that's just one of pre-programmed random behaviors.
Comment: @SF. That sort of thing usually gets called "bug". ;)
Answer: Calves will only jump when certain things are in front of them and they're trying to get across/through, including:

One-block high jumps
Fences (and they fail)
Half Slabs
Blocks that are slightly less than one block in height, including soulsand and farmland (1/16 shorter than a normal block)
Water (jump continuously as they swim)
holes (jump continuously to attempt to get out).

Not sure if there are any others. If I find any I will edit my answer.

Do calves jump?


conky keeps grabbing focus and shortcuts and desktop switching does not work

Question: I run into this issue recently when I tried to use Conky with Compiz & Unity on Ubuntu 16.04. Whenever I close some application I am focused to Conky and can't use shortcuts or switch desktops. Is there a way to prevent this?
Comment: I don't know if you or others are interested but I use ***Unity Tweak Tool*** for high DPI scaling and there are no problems with ***Conky*** interrupting the flow of other applications or shortcuts.
Answer: Yes! Install Compiz configuration manager and compiz plugins:
sudo apt install compizconfig-settings-manager compiz-plugins

now open compiz manager and enable window rules plugin:

and and add class=Conky to No focus line:

now simply set window class in conky:
own_window_class = 'Conky',

and log-off and log in again.
my whole Conky window setup:
own_window_class = 'Conky',
own_window_argb_visual = true,
own_window_argb_value=0,
own_window_type='dock',
own_window=true,
own_window_transparent=true,
own_window_hints='undecorated,below,sticky,skip_taskbar,skip_pager',


find limit of $a_n=\frac{1}{(n+1)^2}+\frac{1}{(n+2)^2}+...+\frac{1}{(2n)^2}$

Question: finding limit of $a_n=\frac{1}{(n+1)^2}+\frac{1}{(n+2)^2}+...+\frac{1}{(2n)^2}$
I know that i have to use Stolz Cesaro theorem, but the problem is that i need second sequence.
Answer: The limit is $0$:
$\displaystyle\frac1{(n+k)^2}\le\frac1{n^2}$ for $1\le k\le n$, so $\displaystyle 0\le a_n\le \frac{n}{n^2}=\frac1n\to0$.
Let me add two remarks: First of all, $\sum_n a_n$ diverges, because if fact $a_n$ grows like $1/n$: $\displaystyle\frac1{(n+k)^2}\ge\frac1{(2n)^2}$ for $1\le k\le n$, so $\displaystyle a_n\ge \frac{n}{(2n)^2}=\frac1{4n}$.
Second, the above suggests to study $\lim_{n\to\infty}n a_n$. Recognizing this as a Riemann sum is the key: Note that
 $$ n\sum_{k=1}^n\frac1{(n+k)^2}=\frac1n\sum_{k=1}^n\frac1{(1+k/n)^2}, $$
which we should recognize as a Riemann sum for $\displaystyle \int_0^1\frac1{(1+x)^2}\,dx$, so the two expressions coincide when $n\to\infty$, and we see that
 $$\lim_{n\to\infty}na_n=\int_0^1\frac1{(1+x)^2}\,dx=\left.\frac{-1}{1+x}\right|_0^1=\frac12. $$
To illustrate the rate of convergence, Sage evaluates $na_n$ when $n=200$, as $0.498128645813151$; when $n=2000$, as $0.499812536458331$; and when $n=20000$, as $0.499981250364583$.
Comment: thank you. I haven't thought, that it might be so easy.
Comment: Make sure this is what is being asked, as opposed to determining the convergence of $\sum a_n$.
Comment: elegant one. nice answer.
Comment: @Kacper If you really like the answer ,you may consider to accept it by clicking the "right" sign on the left hand side of the answer as It will reduce the number of unaccepted answers.
Comment: (It would be nice to have a "calculus-free" argument for $na_n\to1/2$.)
Answer: HINT:
$$S=\frac{1}{(n+1)^2}+\frac{1}{(n+2)^2}+...+\frac{1}{(2n)^2}=\sum_{1\le r\le 2n}\frac1{r^2}-\sum_{1\le r\le n}\frac1{r^2}$$
Putting $2n=m$ in the first sum $$S=4\sum_{1\le r\le m}\frac1{r^2}-\sum_{1\le r\le n}\frac1{r^2}$$
Now use this
Comment: @labbhattacharjee You can't replace $m = 2n$, since you're summing over all $1 \leq r \leq 2n$, not just the even ones.
Comment: but answer is seems zero. are we getting zero here?
Comment: @GA316, no.  I am trying to figure out the mistake.
Comment: one small doubt. are you summing over r?
Comment: @GA316, yes, from $n+1$ to $2n$
Comment: I cant find where is the mistake really. curious to know.
Comment: @GA316, I'm seriously eager to know the same:)
Answer: $$a_n=\frac{1}{n^2}\left( \frac{1}{(1+\frac1n)^2}+\frac{1}{(1+\frac2n)^2}+...+\frac{1}{(1+\frac{n}n)^2} \right)=\frac{1}{n}\left[\frac{1}{n}\left( \frac{1}{(1+\frac1n)^2}+\frac{1}{(1+\frac2n)^2}+...+\frac{1}{(1+\frac{n}n)^2} \right)\right]$$
Now, apply  S-C to
$$a_n=\frac{ \left( \frac{1}{(1+\frac1n)^2}+\frac{1}{(1+\frac2n)^2}+...+\frac{1}{(1+\frac{n}n)^2} \right)  }{n^2}$$
But this is an overkill, it is easy to see that the top is $\leq 1+1+1..+1=n$.
P.S.
$$\frac{1}{n}\left( \frac{1}{(1+\frac1n)^2}+\frac{1}{(1+\frac2n)^2}+...+\frac{1}{(1+\frac{n}n)^2} \right)$$
is a Riemann sum, thus convergent, and $\frac{1}{n}$ converges to $0$.
Alternately, if you don't know integrals,apply S-C to
$$a_n=\frac{ \left( \frac{1}{(1+\frac1n)^2}+\frac{1}{(1+\frac2n)^2}+...+\frac{1}{(1+\frac{n}n)^2} \right)  }{n^2}$$
Comment: I had wondered when the Stolz–Cesàro theorem was going to show up. Do you see a way of adapting its use to verify that $na_n\to1/2$?
Comment: @AndresCaicedo Since $na_n$ is a Riemann sum, I don't see how one can use SC to calculate the integral.  Maybe if one sues SC for something like $2^na_{2^n}$.
Answer: You can solve by another method . This must be interesting to you.
Hint : $lt_{n \rightarrow \infty} $ $\frac{1}{n} \sum_{k=1}^{n} f(\frac{k}{n})$ $ =  $ $\int_0^1 f(x) dx$ where $f$ is in $C[0,1]$
Comment: thanks but i'm in highschool and i  haven't had integrals yet.
Comment: ok. I will give detailed answer. some time it may help you.


call function when click button

Question: i have simply js file but i can't call function with parameter
the code
function removetr(str){
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(document).ready(function(){
$("input.buttonno1").click( removetr(1) );
});

the class of inputs that i want to remove it's values are g1,ga1 and gb1
i want to note that if i change the code to
function removetr(){
str=1;
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(document).ready(function(){
$("input.buttonno1").click( removetr );
});

it's work
Answer: You need to pass a function reference to an event handler, your current code is calling the function directly. Either build your function as an event handler, or pass an anonymous function reference to the click handler.
as event handler:
function removetr(e) {
    var str;
    str = e.data.str;
    $(".g"+str).val("");
    $(".ga"+str).val("");
    $(".gb"+str).val("");
}

$(function () {
    $("input.buttonno1").click({str: '1'}, removetr);
});

as anonymous function reference:
function removetr(str) {
    $(".g"+str).val("");
    $(".ga"+str).val("");
    $(".gb"+str).val("");
}
$(function () {
    $("input.buttonno1").click(function () {
        removetr(1)
    });
});

call function when click button


How can I leave loop when got correct result

Question: I have loop that search for some name.
Result returned as list on each entered character, when word found, I want to clic it and leave loop, but it starts over until use all chars from Name.
var genArr = name.split('')
        cy.wrap(genArr).each(($el, ind, $list) => {
            cy.get('parent').children('chils').type(genArr[ind]).then(()=>{
                cy.wait(0.5)
                if (ind > 2) {
                    cy.get('list').its('length').then((size) => {
                        if (size == 1) {
                            cy.get('list').eq(0).click()
                            //here I wish to stop .each()
                        }else if(ind==genArr.length&&size==0){
                            throw new Error('Search: name wasn\'t found')
                        }
                    })
                }
            })
        })

Comment: I'm just guessing: Would return; work?
Comment: nope with return i got this:
```CypressError: cy.then() failed because you are mixing up async and sync code.
In your callback function you invoked 1 or more cy commands but then returned a synchronous value.
Cypress commands are asynchronous and it doesn't make sense to queue cy commands and yet return a synchronous value.
You likely forgot to properly chain the cy commands using another cy.then().
The value you synchronously returned was: 'true'```
Comment: just 'return;' skipped at all, loop continues
Answer: Looks like you'll want to return false based on the documentation:

https://docs.cypress.io/api/commands/each.html#Return-early


Properties of valuation map

Question: It seems not so hard to prove but how can we prove by induction. Let $K$ be a field and $\nu$ be a valuation map. If $a_{1} + a_{2} + ... + a_{n} = 0$ then prove that $\nu(a_{i}) = \nu(a_{j})$ for some $i \neq j$, where $a_{1}, a_{2},...,a_{n} \in K$. Thanks
Answer: Prove by induction on $n$ the following: if $v(a_1)>\cdots >v(a_n)$, then $v(a_1+\cdots+a_n)=v(a_n)$.
Comment: Thanks YACP. We have $a_{1} + a_{2} + ... + a_{n} = 0$. If $\nu(a_{1})> \nu(a_{2})>...> \nu(a_{n})$ then $\nu(a_{n}) = \nu(0) = \infty$, which is a contradiction because $a_{n}\neq 0$. Thus we must have $\nu(a_{i}) = \nu(a_{j})$ for some $i\neq j$.
Comment: @ YACP thanks. Still I could not figure out where did you use $a_{1} + a_{2} + ... + a_{n} = 0$.
Comment: @Rajesh I didn't use this (what I said is true for any elements $a_i\in K$). But I've let you the pleasure to finish the proof and you did this in your first comment. Hope all is clear now.

Properties of valuation map


PHP - Regex to get integer value that formatted separated by character

Question: If I have a string like this :
TAX ID NO. 01.000.589.0.055.000

My goal is, I want to get the integer digit after tax phrase, which is 010005890055000
So far I write like this
/(tax id no)\s*[^A-Za-z0-9]?\s*\K\d+/i

but It still not true because sometimes user wrote like this:
TAX ID. 01.000.589.0.055.000 or
TAX ID : 01.000.589.0.055.000 or
TAX ID 01.000.589.0.055.000 or
TAX: 01.000.589.0.055.000

even user wrote directly into a prefect integer digit
TAX ID NO. 010005890055000

Please advise
This is all my possibilities:

Non Formatted
JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID NO. 010005890055000
Formatted
JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID NO. 01.000.589.0.055.000
With different tax phrase
JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX 010005890055000
JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID 01.000.589.0.055.000
JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID. 010005890055000
In beginning a sentence
TAX ID. 010005890055000 , JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA
TAX ID. 01.000.589.0.055.000 , JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA

So much thank you...
Answer: You can make use of this:
/(?:tax\s*(?:id\s*)?).*?(\d[\d\.]+)/i
The first group checks for tax with id being optional. It then grabs the first digit and all digit and . and groups it under $1
Regexr
Answer: It looks like your only consistent keyword is TAX, so you can grab digits (with dots and dashes) after it with the regex ~TAX.*?\.? *?([\d\.-]+)~i, then strip non-digits (if desired). Here's an example test:
$data = "JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID NO. 010005890055000
JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID NO. 01.000.589.0.055.000
JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX 010005890055000
JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID 01.000.589.0.055.000
JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID. 010005890055000
TAX ID. 010005890055000 , JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA
tax ID. 01.000.589.0.055.000 , JL
TAX ID. 01.000.589.0.055.000 , JL. CACING RT 007/008 CAKUNG, JAKARTA TIMUR 13910 INDONESIA
JL. CAKUNG CILINCING KP BARU RT 007/008 CAKUNG BARAT, CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID NO. 01.109.421.6-902.000";

foreach (explode("\n", $data) as $line) {
    preg_match("~TAX.*?\.? *?([\d\.-]+)~i", $line, $m);
    echo preg_replace("~\D~", "", $m[1]) . "\n";
}

Output:
010005890055000
010005890055000
010005890055000
010005890055000
010005890055000
010005890055000
010005890055000
010005890055000
011094216902000

Try it!
Comment: Can you list all of your possible input cases in the question from the beginning? It's not helpful for you or us to continually adjust the requirements.
Comment: Working as charm, thanks.
Sorry if I asked not clearly.Basically from my bad english.
Comment: Sorry, it is not in a line.
Comment: OK, this is just an example. `preg_replace("~\D~", "", $line)` works on all of your test cases regardless of whether they're individual strings or not. If not, let me know what sort of input you are dealing with that isn't working and I'll update.
Comment: Thanks for the effort, but how with formatted number as explained above ?
Comment: Sorry, I'm not sure what you're asking. Your expected output is `010005890055000` and this is what this emits.
Comment: Sorry, it for example, people can write like this JL. CAKUNG CILINCING KP BARU RT 007/008 CAKUNG BARAT, CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID NO. 01.109.421.6-902.000
Comment: This handles all of your tests.
Comment: Oke, So much thank you, i dont see the preg_replace after preg_match. Sorry, my bad.
Comment: and also for the tax in lowercase, i still struggle to preg_match them like ~TAX.*?\.? *?([\d\.-]+)+/i~
Comment: Put the `i` after the end delimiter `~`. See update.
Answer: You can use preg_replace to remove all but numbers.
preg_replace('/[^\d]/', '', $str);

see output: https://3v4l.org/Ne3fo

To answer the new requirement:
Use substr and strpos to remove the part up to "tax".
$arr = ["TAX ID. 01.000.589.0.055.000 or",
"TAX ID : 01.000.589.0.055.000 or",
"TAX ID 01.000.589.0.055.000 or",
"TAX: 01.000.589.0.055.000",
"ARU RT 007/008 CAKUNG BARAT, CAKUNG, JAKARTA TIMUR 13910 INDONESIA TAX ID NO. 010005890055000"];

foreach($arr as $str){
    echo preg_replace('/[^\d]/', '', substr($str, stripos($str, "tax"))) . "\n";
}

https://3v4l.org/btDAq
Comment: in that case the output becomes 13910013285705007000. Keep in mind what your question says.
Comment: Clearly after 'tax' phrase. Thanks
Comment: *If I have a string like this :* and *but It still not true because sometimes user wrote like this:*. Nothing is clear unless you make it clear!
Comment: Sorry, basically its part of long string, ex "JAKARTA TIMUR 13910 INDONESIA TAX ID 01.328.570.5-007.000"
Answer: You can use this regex, where except TAX part, I have made everything that comes in middle between tax and numbers as optional. Use this regex and capture group1
/tax(?:.*?)\s+([\d.]+)/i

Demo
Once you get digit and dot part, remove all dot characters from it.
Here is a sample php code,
$arr = ["TAX ID NO. 01.000.589.0.055.000","TAX ID. 01.000.589.0.055.000","TAX ID : 01.000.589.0.055.000","TAX ID 01.000.589.0.055.000","TAX: 01.000.589.0.055.000", "TAX ID NO. 010005890055000"];

foreach ($arr as &$value) {
    preg_match('/tax(?:.*?)\s+([\d.]+)/i', $value, $matches);
    echo $value . " --> " . preg_replace('/\./','',$matches[1]) . "\n";
}

This prints following output,
TAX ID NO. 01.000.589.0.055.000 --> 010005890055000
TAX ID. 01.000.589.0.055.000 --> 010005890055000
TAX ID : 01.000.589.0.055.000 --> 010005890055000
TAX ID 01.000.589.0.055.000 --> 010005890055000
TAX: 01.000.589.0.055.000 --> 010005890055000
TAX ID NO. 010005890055000 --> 010005890055000

Comment: I believe this one could work even with the new string