text:
Q: How do I find the example of a continuous surjective function $f: X \rightarrow Y$ such that inverse image of dense set is not dense? How do I find the example of a continuous surjective function $f: X \rightarrow Y$ such that inverse image of dense set is not dense?
Can anyone suggest some hints for this question?

A: Hint: what if $X$ has the discrete topology?

A: What about
$$\begin{array}{l|rcl}
f : & X= \mathbb R & \longrightarrow & Y = [0,\infty) \\
    & x & \longmapsto & \begin{cases}0 & x <0\\ x & x \ge 0\end{cases}\end{array}$$
$(0,\infty)$ is dense in $Y$ but $f^{-1}[(0,\infty)] = (0,\infty)$ is not dense in $\mathbb R$.


text:
Q: SQL Server : Parent/Child - Find deepest Child with status failed I have the following table:
STEPID|RUN_ID|SERIAL |PARENT|STEPNAME                                  |STATUS
171730|  3101|0103107|171696|6.9 - Load Program YXZ                    |Failed
171740|  3101|0103107|171730|6.9.5 - Step Test. Program YXZ Error Code |Failed
171741|  3101|0103107|171730|6.9.6 - Step Test. Program YXZ - Part 1   |Failed
171742|  3101|0103107|171730|6.9.7 - Step Test. Program YXZ - Part 2   |Failed
171743|  3101|0103107|171730|6.9.8 - Step Test. Program YXZ - Part 3   |Failed
171744|  3101|0103107|171730|6.9.9 - Step Test. Program YXZ - Part 4   |Failed
171745|  3101|0103107|171730|6.9.10 - Step Test. Program YXZ - Part 5  |Failed
171785|  3102|0103107|171751|6.9 - Load Program YXZ                    |Failed
171788|  3102|0103107|171785|6.9.4 - Run Test - Monitor                |Failed
171789|  3102|0103107|171788|6.9.4.1 - Step Test. Program YXZ - Part 11|Failed
171790|  3102|0103107|171788|6.9.4.2 - Step Test. Program YXZ - Part 12|Failed
171791|  3102|0103107|171788|6.9.4.3 - Step Test. Program YXZ - Part 13|Failed
171792|  3102|0103107|171788|6.9.4.4 - Step Test. Program YXZ - Part 14|Failed
171793|  3102|0103107|171788|6.9.4.5 - Step Test. Program YXZ - Part 15|Failed
171794|  3102|0103107|171788|6.9.4.6 - Step Test. Program YXZ - Part 16|Failed
171795|  3102|0103107|171785|6.9.5 - Step Test. Program YXZ Error Code |Failed
171796|  3102|0103107|171785|6.9.6 - Step Test. Program YXZ - Part 1   |Failed
171797|  3102|0103107|171785|6.9.7 - Step Test. Program YXZ - Part 2   |Failed
171798|  3102|0103107|171785|6.9.8 - Step Test. Program YXZ - Part 3   |Failed
171799|  3102|0103107|171785|6.9.9 - Step Test. Program YXZ - Part 4   |Failed
171800|  3102|0103107|171785|6.9.10 - Step Test. Program YXZ - Part 5  |Failed

I have 2 unique RUN_ID's, for the same serial. Foreach RUN_ID, I need to find childs, on the deepest level, with the status failed. From the above table I would like to find:
STEPID|RUN_ID|SERIAL |PARENT|STEPNAME                                  |STATUS
171745|  3101|0103107|171730|6.9.10 - Step Test. Program YXZ - Part 5  |Failed
171794|  3102|0103107|171788|6.9.4.6 - Step Test. Program YXZ - Part 16|Failed
171800|  3102|0103107|171785|6.9.10 - Step Test. Program YXZ - Part 5  |Failed

The 6.9 could be a valid child, but because it has childs with the failed status, it needs to be excluded. I don't expect more levels than 4, like 6.9.4.6.
It is possible to solve this in pure SQL ? I have tried to substring the level hierarchy, and expose it as separate columns and do some group by / CTE, but I can't get my head around it.
STEPID|RUN_ID|SERIAL |PARENT|Level1|Level2|Level3|Level4|STATUS
171785|  3102|0103107|171751|     6|     9|  NULL|  NULL|Failed
171788|  3102|0103107|171785|     6|     9|     4|  NULL|Failed
171789|  3102|0103107|171788|     6|     9|     4|     1|Failed
171790|  3102|0103107|171788|     6|     9|     4|     2|Failed

Update #1:
Anand asked if the stepname starts on a single digit. It does on the real table, but I have filtered that out in my current CTE, because an error can't occur on that level.
Update #2:
A paste bin link for creation of the table (faking the CTE) and insert statements: http://pastebin.com/7JmP99KP

A: It got a little long winded parsing out the child node as an integer without it ending up as copy/paste speghetti, but at least you can walk the CTE's one by one to understand how I'm getting there.
WITH
    StepWithTrimmedName AS
    (
        SELECT
            *,
            SUBSTRING(s.STEPNAME, 1, CHARINDEX(' - ', s.STEPNAME) - 1) AS TrimmedName
        FROM
            dbo.Temp_Steps s
    ),
    StepWithPeriod AS
    (
        SELECT
            *,
            CHARINDEX('.', REVERSE(s.TrimmedName)) AS Period
        FROM
            StepWithTrimmedName s
    ),
    StepWithCharacterLength AS
    (
        SELECT
            *,
            CASE
                WHEN s.Period = 0 THEN 1
                ELSE s.Period - 1
            END AS CharacterLength
        FROM
            StepWithPeriod s
    ),
    StepWithStartPosition AS
    (
        SELECT
            *,
            LEN(s.TrimmedName) - s.CharacterLength + 1 AS StartPosition
        FROM
            StepWithCharacterLength s
    ),
    StepWithRowNumber AS
    (
        SELECT
            *,
            ROW_NUMBER() OVER (PARTITION BY s.PARENT ORDER BY
                CAST(SUBSTRING(s.TrimmedName, s.StartPosition, s.CharacterLength) AS INT) DESC) AS RowNum
        FROM
            StepWithStartPosition s
        WHERE
            s.[Status] = 'Failed'
    )
SELECT
    *
FROM
    StepWithRowNumber s
WHERE
    s.RowNum = 1 AND
    NOT EXISTS
    (
        SELECT *
        FROM
            StepWithRowNumber c
        WHERE
            c.PARENT = s.StepId
    )
ORDER BY
    S.SERIAL,
    s.RUN_ID,
    s.PARENT,
    s.RowNum;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding column to table and automatically UNION tables afterwards I have the following problem:
I have a table with distinct pairs of ID and Indicator.
    Table A:
    ID         Indicator
    ----------------------
    1            1
    1            2
    1            3
    2            1
    2            2
    2            3
    ----------------------

And a second table with distinct names.
    Table B:
    Names
    -------
    John
    Lea
    Peter
    --------

What I want is a column in table A with the names of Table B for every ID-Indicator pair:
    Outcome:
    ID         Indicator    Names
    ----------------------------------
    1            1          John
    1            2          John
    1            3          John
    2            1          John
    2            2          John
    2            3          John
    1            1          Lea
    1            2          Lea
    1            3          Lea
    2            1          Lea
    2            2          Lea
    2            3          Lea
    1            1          Peter
    1            2          Peter
    1            3          Peter
    2            1          Peter
    2            2          Peter
    2            3          Peter
    ----------------------------------

In reality Table B, with the names, is really long, so a manual solution like:
SELECT ID, Indicator, Names = 'John'
FROM TableA
UNION
SELECT ID, Indicator, Names = 'Lea'
FROM TableA

Is not feasible. Is there a non-manual solution to this problem?
Any help is highly appreciated!

A: You want to join each row in TableA with each row in TableB, this is known as a cross join, as commented. The number of rows output will be A * B.
If you want all columns from both tables the syntax is simply
select *
from TableA cross join TableB


text:
Q: não entendi como funciona o valor (self) em "cidade.estado = self " dentro da função adiciona_cidade() class Estado:

    def __init__(self, nome, sigla):
        self.nome = nome
        self.sigla = sigla
        self.cidades = []

    def adiciona_cidade(self, cidade):
        #essa linha abaixo que eu não entendi o que significa
        cidade.estado = self
        self.cidades.append(cidade)

    def populacao(self):
        #O loop abaixo significa: para cada item de
        #c.populacao (que é: cidade.populacao) em self.cidades.
        return sum([c.populacao for c in self.cidades])

class Cidade:

    def __init__(self, nome, populacao):
        self.nome = nome
        self.populacao = populacao
        self.estado = None

    def __str__(self):
        return "Cidade (nome=%s, populacao=%d, estado=%s)" %(
            self.nome, self.populacao, self.estado)

# Populações obtidas no site da Wikipédia
# IBGE estimativa 2012
am = Estado("Amazonas", "AM")
am.adiciona_cidade(Cidade("Manaus", 1861838))
am.adiciona_cidade(Cidade("Parintins", 103828))
am.adiciona_cidade(Cidade("Itacoatiara", 89064))

sp = Estado("São Paulo", "SP")
sp.adiciona_cidade(Cidade("São Paulo", 11376685))
sp.adiciona_cidade(Cidade("Guarulhos", 1244518))
sp.adiciona_cidade(Cidade("Campinas", 1098630))

rj = Estado("Rio de Janeiro", "RJ")
rj.adiciona_cidade(Cidade("Rio de Janeiro", 6390290))
rj.adiciona_cidade(Cidade("São Gonçalo", 1016128))
rj.adiciona_cidade(Cidade("Duque de Caixias", 867067))

for estado in  [am, sp, rj]:
    print("Estado: %s Sigla: %s" % (estado.nome, estado.sigla))
    for cidade in estado.cidades:
        print("Cidade: %s População: %d" % (cidade.nome, cidade.população))
    print("População do Estado: %d\n" % estado.população())

A: O self em Python é equivalente ao this existente em Javascript, Java, C++ e outras - e diz respeito ao próprio objeto.
No caso, você está vendo o self dentro de um método da classe Estado - então o self é o próprio estado que tem que ser colocado na cidade. Ele simplesmente preenche essa informação no outro objeto (cidade). .
Ao contrário de outras linguagens, no entanto, o self no Python é explícito: ele é recebido como primeiro parâmetro dentro de um método, e em geral é chamado de self - e não "aparece do nada" como o this nas linguagens que citei. O nome "self" é usado por convenção, e você poderia usar qualquer outro nome (no primeiro parâmetro e na atribuição), que o programa funcionaria do mesmo jeito.


text:
Q: How to display non-existing images the way IE/Opera does? My Firefox 3.0.4 does not display non-existing images at all, or it displays the image alt as plain text (if available).
This way I would have no idea that there is supposed to be an image there.
Does anyone know if there is a way to make it work like IE/Opera? (ie. display a box even if the image file doesn't exists) - plugin or anything?
Test image:

A: There is a setting in about:config that is supposed to do just this: browser.display.show_image_placeholders. However, it doesn't do anything on its own.
You need to add a rule to userContent.css like this:
/*
 * Show image placeholders
 */
@-moz-document url-prefix(http), url-prefix(https), url-prefix(file) {
  img:-moz-broken {
    -moz-force-broken-image-icon: 1;
    width: 24px;
    height: 24px;
  }
}

Then images will be displayed like this:

Note that this hides the alt text, unlike Chrome which shows the alt text next to the placeholder.

A: You could get the Firebug Plugin. It won't change how the images show up, but it does have a network tab that you can click to see which resources were gotten by firefox (and how fast). As well, it will tell you what images, js files and css files it was not able to get. It's incredibly handy for web development.
It also has a ton of other great features like JS debugging, and so much more.

A: There's an experimental Force Image Placeholders plugin which attempts to do what you request.  I haven't used it, but it's worth a try.

A: Here's another addon-based workaround.

*

*Get the Stylish addon for Firefox, allowing you to apply your own styling information.

*Add a background to all  tags.  If the image loads, you won't see it.

But be warned that, if any images rely on transparency, the new default background will show through.

A: My extension, FeatureFix, now contains a comprehensive section in its configuration GUI ("advanced/developer tweaks") to configure broken/loading image placeholders.

A: Along the lines of Pim Jager's suggestion, but it seems as though you'll need to force the image to display with something like "display: block;". This has the advantage of allowing you to specify additional styles via CSS that will show if the image doesn't - e.g. a background-color, or even a background-image. YMMV.

A: As far as i know there is no plugin, Images should have a width and height specified like so:

or

Then firefox will reserve the appropiate space for the images.

A: Nothing works, based on experience and all research on tis matter, Firefox will not (in Windows anyway) display broken icon/image placeholders icon not matter what css and about:config settings.
Worst is all other browser do it by default, so if you want to know whats really going on dump Firefox.


text:
Q: How i can convert a mdb file to mysql file or mysql commands with PHP? Is it possible to create mysql file or mysql commands from mdb (Microsoft access database) 2002-2003 format using PHP?
Actually i have a mdb file which have 8-10 table and i want to copy that whole data to my mysql database.
I know it is open question. Just need a starting point or if you can refer me some online helping material. That would be great. Thanks in advance guys.

A: U can use ODBC to connect to Access base, and make SQL queries.


text: Q: Write a one column of each row as separate file in hdfs by using pyspark I have a use case where the program needs to read one column from csv file and  write column in a data frame as a separate file to hdfs. For example if I have 10 lines in data frame means 10 output files need to be generate


text:
Q: Defining a set/get interface without using matlab hgsetget abstract class I generally find the set/get interface defined in hgsetget very useful for setting and getting multiple parameters at the same time. I recently found it was especially suited for object construction.
Example:
classdef testclass < hgsetget

    properties
        A
        B
        C
        D
    end

    methods
        function obj = testclass(varargin)
            if ~isempty(varargin)
               set(obj,varargin{:})
            end
        end
    end
end

Usage:
>> a = testclass('A',1,'B',2)

a =

  testclass handle

  Properties:
    A: 1
    B: 2
    C: []
    D: []

Despite the slowness of this interface I'm really happy of the flexibility it provides.
What is more annoying for my application is that I obtain a handle class (by inheritance from hgsetget).
To circumvent this my first guess was to construct an abstract class with my set/get definition inside. Very simply written it gives:
classdef (Abstract) myAbstractClass

    methods

        function obj = set(obj,varargin)
            for i = 1:2:length(varargin)
                obj.(varargin{i}) = varargin{i+1};
            end
        end

        function val = get(obj,varargin)
            val = cell(length(varargin),1);
            for i = 1:length(varargin)
                val{i} = obj.(varargin{i});
            end
        end

    end

end

and then set it as superclass for my test class
classdef testclass < myAbstractClass

    properties
        A
        B
        C
        D
    end

    methods
        function obj = testclass(varargin)
            if ~isempty(varargin)
                set(obj,varargin{:})
            end
        end
    end
end

However I must misunderstand something in the construction mechanism because here is what happens:
>> a = testclass('A',1,'B',2)

ans =

  testclass

  Properties:
    A: 1
    B: 2
    C: []
    D: []

  Methods, Superclasses

a =

  testclass

  Properties:
    A: []
    B: []
    C: []
    D: []

  Methods, Superclasses

If somebody knows the reason of this behavior, I'm totally open to her/his explanations
Thank you in advance
JM

A: Overall your design looks good, but within your constructor method testclass, you need to write
obj = set(obj,varargin{:});

Because you are using a value class rather than a handle class, you need to retrieve the output of your set method, otherwise you'll have set the property of something, and then discarded it and returned a completely different (and empty) obj as output.
Also, you need to add a semi-colon after the call to set; otherwise it will display the intermediate something.
You may also want to revise your opinion of handle classes; they're really very natural to use (just my opinion, but more natural in an OO context than value-behaviour).


text:
Q: Given an array of ints, what is the most efficient way to split the array down the middle into two arrays of shorts? It struck me there must be a clever way to do this.  This isn't for homework, or work or anything.  I was just noodling around with a file format that has data interleaved.
So, in generic C/C++, (or whatever) given some array
int x[] = ...

is there a clever way of splitting it into two short arrays
short sa1[], sa2[]

such that the int array is split down the middle
x[i] = 1111111111111111 1111111111111111
             sa1[i]         sa2[i]

Edit: Sorry if this is not phrased well. For each i-th element of the int array, the left-most 16 bits become the i-th element of one array, and the right-most 16bits become the i-th element of a 2nd array.
so given
x[i] = 0001111111111111 1111111100011111

then
sa1[i] = 0001111111111111
sa2[i] = 1111111100011111

I'm looking for non-obvious answers that do not loop over each element and shift and mask each element.  That's easy :)

A: There's a lot of ways to do this:
Assumptions:

*

*short is 16 bits.

*int is 32 bits.

Method 1: (A simple loop)
for (int i = 0; i < size; i++){
    int tmp = x[i];
    sa1[i] = (tmp      ) & 0xffff;
    sa2[i] = (tmp >> 16) & 0xffff;
}

Method 2: SSE2
for (int i = 0; i < size / 8; i++){
    __m128i a0 = ((__m128i*)x)[2*i + 0];
    __m128i a1 = ((__m128i*)x)[2*i + 1];

    a0 = _mm_shufflelo_epi16(a0,216);
    a1 = _mm_shufflelo_epi16(a1,216);
    a0 = _mm_shufflehi_epi16(a0,216);
    a1 = _mm_shufflehi_epi16(a1,216);
    a0 = _mm_shuffle_epi32(a0,216);
    a1 = _mm_shuffle_epi32(a1,216);

    ((__m128i*)sa1)[i] = _mm_unpacklo_epi64(a0,a1);
    ((__m128i*)sa2)[i] = _mm_unpackhi_epi64(a0,a1);
}

This last example is very fast if the loop is further unrolled. I won't be surprised if this can beat all byte-manipulation libraries.
However, it has the following restrictions:

*

*The data must be aligned to 16 bytes.

*The number of iterations must be divisible by 8.

*It requires SSE2.

The first two of these can be solved by cleanup code. It's messy, but if you really desire performance, it may be worth it.
EDIT:
Yes this violates strict-aliasing, but it's nearly impossible to use SSE intrinsics without doing so.

A: If int is exactly two shorts on your platform, you can just reinterpret_cast the int array into short array, then take even/odd elements.
Note however, that size of int versus short is not guaranteed (other than short cannot be larger than int). For example int may be equal to short or it may be more than 2 shorts. Even the absolute size of int is not guaranteed (typical sizes are 4 and 8 bytes).
For truly portable solution, you'll probably be better off mapping the exact format of the file you are trying to interpret into bit fields.

A: You will need to know the length of x, but you could do something similar to:
#include <stdio.h>

int main(int argc, char * argv[])
{
    int x[] = {1, 2, 3, 4, 5, 6};
    int xlen = 6;

    short * a = &x[0];
    short * b = &x[xlen/2];

    printf("%d\n%d\n", a[0], b[0]);
}

a points to the beginning of the original int array, and allows you to index in short increments. Same deal with b, except it starts from the middle of the original int array.
I would call this clever, but you will get a warning from gcc about incompatible pointer types. This is the kind of thing I might do in an embedded environment, but I would make sure it doesn't cause any security issues in a less controlled environment.


text:
Q: Convert GIF images to PNG format, 32 bits depth Here is a solution to convert GIF images to PNG format. The problem is that the generated PNG images are in 8 bits depth (in my case at least).
Is there a way to force them to be in 32 bits depth? The best would be using the javax.imageio.ImageIO library.

A: Just convert the BufferedImage, redrawing a copy with the desidered colour model. Not extremely efficient, but practical:
      File input = new File("/tmp/input.gif");
      File output = new File("/tmp/output.png");
      BufferedImage im1 = ImageIO.read( input );
      BufferedImage im2 = new BufferedImage(im1.getWidth(), im1.getHeight(),
                BufferedImage.TYPE_4BYTE_ABGR);
      im2.getGraphics().drawImage(im1, 0, 0, null);
      ImageIO.write(im2 , "png", output);


text:
Q: How to configure "Same as Display" as processing extent by default in ModelBuilder? I'm working on a very simple model for creating a path from a selected point to the closest polyline, in this model I used a Cost Distance and Cost Path tool for creating the more feasible track (considering the slope).
Everything works fine, but because I'm using a Cost Raster from a very large area (whole México country) the processing is very slow, so I set the processing extent as "Same as Display", the problem comes when I select another point from a different extent, the processing extent have to be configured in the model as "Same as Display" other way it is automatically set as "As Specified Below"

What I want to know is if there is a way to configure the Processing Extent as "Same As Display" and it stay like that as default doesn't matter where I select the point. I want this model to be published on web but I don't want to add the processing extent as parameter


text:
Q: How to Change Sound Wave Swift I found how to create Sound wave From FDWaveformView Pods , but I can't modify to create a this type of wave screenshot below:
Here is what I am trying to do:-

The screenshot is taken from iPhone:-

This code creates sine wave but I need to create pulse waves:-
    soundWaveView.delegate = self
    soundWaveView.alpha = 0.0
    soundWaveView.audioURL = mainTrackURL
    soundWaveView.zoomSamples = 0 ..< soundWaveView.totalSamples / 3
    soundWaveView.doesAllowScrubbing = false
    soundWaveView.doesAllowStretch = false
    soundWaveView.doesAllowScroll = false
    soundWaveView.wavesColor = UIColor(red: 46/255, green: 188/255, blue: 191/255, alpha: 1)
    soundWaveView.progressColor = UIColor(red: 251/255, green: 237/255, blue: 101/255, alpha: 1)
    do {
        try AVAudioSession.sharedInstance().setActive(true)
        playerSoundWave = try AVAudioPlayer(contentsOf: mainTrackURL!, fileTypeHint: AVFileType.mp4.rawValue)
        songTotalTime = Double((playerSoundWave?.duration)!)
    }
    catch let error {
        print(error.localizedDescription)
    }

Question: How to modify or create sound wave?
Can someone please explain to me how to create and modify sound wave, i've tried to modify but no results yet. Any help would be greatly appreciated.
Thanks in advance.


text:
Q: Why does vim use 99% of CPU when I insert below with a large line above? When I try to insert the code below in vim using o in a Python file that contains a large dictionary on a single line, line 3 below, my terminal window hangs, and CPU usage spikes to 99%.
I have a Python test file that is similar to this:
1 from library import module
2
3 DICT = { <3000-6000 character dictionary on a single line> }
4 KEY = "examplekey"
5
6 def test_func_on_dict():
7    expected_output = 42
8    output = module.call_function(DICT, KEY)
9    assert output == expected_output

As I type o on line 5 the CPU spikes to 99% and I can't interact with the file. If I delete the large single-line dictionary the speed of vim goes back to normal.
As one of the biggest benefits of Vim is its speed of editing, this has started to grate on me pretty fast. I saw "How to find what slows down vim?" about profiling vim but my problem is on insert and not on the load time. I am using vim-plug.
My .vimrc looks like this:
call plug#begin('~/.vim/plugged')
Plug 'junegunn/seoul256.vim'
Plug 'junegunn/goyo.vim'
Plug 'junegunn/limelight.vim'
Plug 'beautify-web/js-beautify'
Plug 'vimwiki/vimwiki'
call plug#end()

99.8 is the CPU % in htop:

It has been suggested my question should be closed because it is similar to "Why is pasting a long one-liner very slow in Vim's insert mode?". I don't think the suggest post answers my question because my long line, the large dictionary, is already present in the file. vim is not slow on paste. vim is slow on o insert below the long line. I think there is something to the issue being the time it takes to re-draw everything as noted in "Why is pasting a long one-liner very slow in Vim's insert mode?" but I do not see an obvious solution to the problem as of yet.
Spreading the dictionary out over many lines fixes the issue. Notably, when in :set paste mode, there is no speed issue with the o insert command below the large dict on a single line. Also, whether in visual mode or paste mode, there is no issue when the cursor is above the large dict and o is pressed. However, I am also interested in why this happens, not just what the fix is.

A: The solution, as present in the update, is to avoid having massively long lines.
I would say it's even poor programming practice not to split the dict across lines for readability.
But it definitely hurts Vim's performance. I have a CSV file of about 500 rows by 500 columns, and I can still edit with reasonable performance. However, I suspect that joining all the lines together would cause the same issue you see.


text:
Q: Delete datetime from SQL database based on hour I'm a python dev, I'm handling an SQL database through sqlite3 and I need to perform a certain SQL query to delete data.
I have tables which contain datetime objects as keys.
I want to keep only one row per hour (the last record for that specific time) and delete the rest.
I also need this to only happen on data older than 1 week.
Here's my attempt:
import sqlite3
c= db.cursor()
c.execute('''DELETE FROM TICKER_AAPL WHERE time < 2022-07-11 AND time NOT IN
    ( SELECT * FROM
    (SELECT min(time) FROM TICKER_AAPL GROUP BY hour(time)) AS temp_tab);''')

Here's a screenshot of the table itself:

A: First change the format of your dates from yyyyMMdd ... to yyyy-MM-dd ..., because this is the only valid text date format for SQLite.
Then use the function strftime() in your query to get the hour of each value in the column time:
DELETE FROM TICKER_AAPL
WHERE time < date(CURRENT_DATE, '-7 day')
  AND time NOT IN (SELECT MAX(time) FROM TICKER_AAPL GROUP BY strftime('%Y-%m-%d %H', time));


text:
Q: Tornado web socket communication on demand? I'm setting up a tornado web socket and want to use it to send log data over my network. Seems to work fine, but:
(1) Can I send data from client to server arbitrarily once the connection is established, or do I have to establish a new connection and use the on_open method to print/work with the sent message every time?
(2) In my client specifically (link): why isn't ws.close() called? Doesn't seem to happen. How can I terminate a connection then?
(3) Is there a better way to identify clients other that connection.request.remote_ip?
Code: Server
import tornado.ioloop
import tornado.web
import tornado.websocket

host = "localhost:2000"

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("
HELLO
")

class EchoWebSocket(tornado.websocket.WebSocketHandler):
    connections = set()
    ips         = set()

    def open(self):
        self.connections.add(self)
        self.ips.add(self.request.remote_ip)
        print("[MASTER]: WebSocket opened by {}".format(self.request.remote_ip))

    def on_message(self, message):
        print("[CLIENT {}]: {}".format(self.request.remote_ip, message))
        [con.write_message("[MASTER]: {}".format(message)) for con in self.connections]

    def on_close(self):
        self.connections.remove(self)
        self.ips.remove(self.request.remote_ip)
        print("[MASTER]: WebSocket closed - Client {}".format(self.request.remote_ip))

def setup():
        return tornado.web.Application([(r"/", MainHandler),
                                        (r"/ws", EchoWebSocket)])

if __name__ == "__main__":
    s = tornado.httpserver.HTTPServer(setup())
    s.listen(2000)
    print("------------- INFO -------------\nStarted Server at {}\nSocket available at /ws".format(host))
    tornado.ioloop.IOLoop.current().start()

Client:
from tornado.websocket import websocket_connect
import tornado
import time

url = "ws://localhost:2000/ws"

class Client(object):
    def __init__(self, url, log=None):
        self.url = url
        self.ioloop = tornado.ioloop.IOLoop.current()
        self.conn = None
        self.log = log

    def start(self):
        websocket_connect(
                        self.url,
                        self.ioloop,
                        callback=self.on_connected,
                        on_message_callback=self.on_message)
        self.ioloop.start()

    def on_connected(self, f):
        try:
            self.conn = f.result()
            self.conn.write_message("Client #1 connected")
        except Exception as e:
            print("[ERROR]: {}".format(e))
            self.conn.write_message("ERROR: {}".format(e))
            self.ioloop.stop()

    def on_message(self, message):
        if message is None:
            print("[ERROR]: No message received")
            self.conn.write_message("[ERROR]: No message received")
            self.ioloop.stop()
        else:
            print(message)

    def close():
        self.conn.close()

if __name__ == '__main__':
    ws = Client(url)
    ws.start()
    ws.close()


text:
Q: I tried to get address from latitude and longitude through list but got IndexOutOfBoundsException every time tried to get the address using latitude and longitude. Same code works on other devices though, address list returns null on some devices(physical)
android version: 11.
MainActivity.java
public void onLocationResult(@NonNull LocationResult locationResult) {
                                    super.onLocationResult(locationResult);

                                    LocationServices.getFusedLocationProviderClient(MainActivity.this)
                                            .removeLocationUpdates(this);

                                    if (locationResult != null && locationResult.getLocations().size() >0){

                                        int index = locationResult.getLocations().size() - 1;
                                        double latitude = locationResult.getLocations().get(index).getLatitude();
                                        double longitude = locationResult.getLocations().get(index).getLongitude();

                                        geocoder = new Geocoder(MainActivity.this, Locale.getDefault());

                                        try {
                                            addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }

                                        String address = addresses.get(0).getAddressLine(0);
                                        String city = addresses.get(0).getLocality();
                                        String state = addresses.get(0).getAdminArea();
                                        String country = addresses.get(0).getCountryName();

                                        AddressText.setText("address: "+ address + "\n" + "city: "+ city + "state: "+ state + "\n" + "country: "+ country);
                                    }
                                }

Error:
2022-05-25 09:36:53.805 29773-29773/com.example.location E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.location, PID: 29773
    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.get(ArrayList.java:437)
        at com.example.location.MainActivity$2.onLocationResult(MainActivity.java:142)
        at com.google.android.gms.internal.location.zzap.notifyListener(com.google.android.gms:play-services-location@@18.0.0:2)
        at com.google.android.gms.common.api.internal.ListenerHolder.zaa(com.google.android.gms:play-services-base@@18.0.1:2)
        at com.google.android.gms.common.api.internal.zacb.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:233)
        at android.app.ActivityThread.main(ActivityThread.java:8010)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)

A: Geocoder is not stable and sometimes stops working, when Geocoder breaks it simply returns an empty list. Unfortunately, there is no way to check if Geocoder is working in advance. The workaround is to connect to the Google Maps web api when your Geocoder returns an empty list. Look at this post for an example of the code.


text:
Q: Set time to reload parent window after form closes I have a drop-down list for categories. I created a popup for new category. When I hit submit the form, a new category is stored in a DB table, which will show on the drop-down list for categories. However, when I submit the form, it closes and reload so quick that the new category is not inserted into the DB table yet. How do I set 5 seconds to reload the parent page after the popup window closes.
My code:
function reloadIt() {
opener.location.reload(true);
self.close();
}

Thanks.

A: You can use setTimeout to "schedule" a function for later:
setTimeout(() => { /*...*/ }, 5000);
edit:
Here's a more fleshed out version, sans arrow syntax:
setTimeout(function() {
  opener.location.reload(true);
  self.close();
}, 5000);

A: function reloadIt() {
    setTimeout(function () {
        opener.location.reload(true);
        self.close();
    }, 5000);
}


text:
Q: A subset of $\mathbb{R}$ is not closed if it does not have any limit points. I just began to study real analysis, and there is this question given by TA confused me.
Let $L\subset\mathbb{R}$, then $L$ is closed if it has no limit points(This is different from it does not contain any limit points according to what he says, and he further adds that in this case $L$ may not contain any convergent sequence as a result).
It is trivial when $L$ is empty since in this case, $L^c$ is $\mathbb{R}$ which is open. But I cannot sort out the case when $L$ is nonempty because the definition of the limit points that
if $x$ is a limit point of $L$ then for every $\epsilon>0$ such that the neighborhood $V_\epsilon(x)$ intercepts some elements of $L$ other than $x$,
forces me to not consider the constant sequence(If we are allowed to consider a constant sequence then it will be handy to construct a counterexample to the claim and so that $L$ can only be an empty set). So I wonder if this claim is justified and so it can be answered with elementary idea.
If possible, no matter this claim is correct or not, I would like to have some examples which address why it is or it isn't. Thanks.

A: Consider the set $S =$$\{0\}\subset\mathbb{R}$
The complement of $S$, $S^c$$= (-\infty,0)\cup(0,\infty)$
Every point of $S^c$ is an interior point and thus is open. Hence, $S$ is closed. Suppose $x\in\mathbb{R}$ is a limit point of $S$. Choose $r = \frac{1}{2} |x|$. Then a neighborhood of $x$ of radius $r$ does not contain $0$, a contradiction. Therefore, $S$ has no limit point.

A: $L\subset {\mathbb R} $ is closed iff $L$ contains all of it's limit points.
$ L' $ : Set of all limit points of $L$ (Derived Set)
Then, $ L $ is closed in $\mathbb{R} $ iff $L' \subset {L}$
In your question, if $L$ contains no limit points then $L' =\emptyset$
and as we know empty set is a subset of every sets, $L' \subset {L} $
And hence, $L\subset {\mathbb{R}} $ is closed.(It's just a particular case of the definition) .
Now come to the sequential definition of limit point,
a point $x\in \mathbb{R} $ is a limit point of $L$ if $\exists (x_n) \subset L$ and $x_n \neq x,\forall n\in \mathbb{N}$ such that $x_n \to x $.
You can prove this two definitions of limit points are infact equivalent. (Assuming you are inside $\mathbb {R}$)
Then, $L\subset {\mathbb{R}}$
is closed if for every sequence $(x_n) \subset L$ and such that $x_n \to x $ $\implies x\in {L}$.
Now, the question is about the validity of constant sequence.
If we allow constant sequence, then every points of $L$ would be a limit point.
And then the way we define limit point,empty set is the only set having no limit points.
So, it depends on your definition i.e the existence of a ponit in every neighborhood of $ x $ distinct from $x$ or not.
But, the standard way to define a limit point that allows a point other that point.

A: One more thing i wanna added is that if we take a sequence in any set and make range set of it then that sequence will be convergent iff range set contains that limit point. But according to your consideration, you are taking a sequence in $L$ ,   $L$ doesn't contains any limit point then range set which will be subset of $L$ offcourse , so $L$ will also not contains any limit points . So there will no convergent sequence in $L$


text:
Q: How to get the node value I am trying to fetch the value for name attribute but unable to do it.
<Person>
    <DOB localDate="2015-07-02" utcDate="2015-07-02" localTime="09:26:00" utcTime="08:26:00" />
    <Info name="Bruce Wayne" Country="GB" Zone="3" />
</Person>

A: Try This:
string str= "";
XmlDocument xdoc = new XmlDocument();
xdoc.Load("Your XML Path");
XmlNodeList elements = xdoc.GetElementsByTagName("Info");
for (int i = 0; i < elements.Count; i++)
{
   str= elements[i].Attributes["name"].Value;
}
MessageBox.Show(str);

A: Unless you have a specific reason for using an XmlDocument, use the newer XDocument instead, linq makes finding xml nodes very easy.
Try this
var name = xDoc.Root.Element("Info").Attribute("name").Value;


text:
Q: How to pass props to child component with Vue Router? I have a Vue component with Navigation and layout that uses a bus to communicate with sub components. The bus is passed as a prop to sub components which then use $emit.
export default class Dashboard extends Vue {

  protected bus: Vue = new Vue();

  mounted() {
    if (this.bus != null) {
      this.bus.$on("save", () => {
        //
      });
    }
  }
}

@Component({ props: ["bus"] })
export default class Child extends Vue {
   protected bus!: Vue;

   save() {
      this.bus.$emit("save");
   }
}

This works fine in the standard case.
In the case of Vue Router how can I inject the bus component from the parent into the children?

A: You should create a bus instance in a separate file that you can import into any other file that needs to use it, instance will persist across all places it is imported.
You can use the data() object instead of passing as props as it will act as a global store but that's what Vuex is for.
// BusDepot.js

import Vue from 'vue'

export const DashboardBus = new Vue({
  data: {
   mySharedValue: 'Its global!'
  }
})

import { DashboardBus } from 'BusDepot'

export default class Dashboard extends Vue {

  created () {

    DashboardBus.$on('save', () => {

      console.log(DashboardBus.mySharedValue)

    });

  }

}

import { DashboardBus } from 'BusDepot'

export default class Child extends Vue {

   save() {
      DashboardBus.$emit('save');
   }
}

If you use Vuex as a central data store to resolve your props pass down issue, you could use the main Vue instance as an Event Bus:
import { DashboardBus } from 'BusDepot'

export default class Dashboard extends Vue {

  created () {
    const vm = this

    vm.$root.$on('dashbaord.save', () => {

      console.log(vm.$store.state.mySharedValue)

    });

  }

}

import { DashboardBus } from 'BusDepot'

export default class Child extends Vue {

   save() {
      this.$root.$emit('dashbaord.save');
   }
}


text:
Q: How do I render multiple languages (e.g. Chinese, cyrillic, english) at once in a legend using matplotlib? I am plotting statistics related to different translations of a word. Using python / matplotlib under Ubuntu I cannot get my legend to show all my languages.
My code below
#!/usr/bin/python

import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('pgf') # This may make things harder; solutions without it are still of interest
# pip3 install matplotlib==3.5
plt.close('all')

fig,ax= plt.subplots(1)
ax.plot(1,1,'.',label='english')
ax.plot(1,2,'.',label='Glück')
ax.plot(1,1,'.',label='доход')
ax.plot(1,1,'.',label='幸福')
plt.legend()
plt.savefig('tmp.pdf')
plt.savefig('tmp.png')

print(matplotlib.__version__)

seems to do fine with various Unicode, but not Chinese. I get the following:

/home/meuser/tmpbug.py:23: UserWarning: Glyph 24184 (\N{CJK UNIFIED IDEOGRAPH-5E78}) missing from current font.

/home/meuser/tmpbug.py:23: UserWarning: Glyph 31119 (\N{CJK UNIFIED IDEOGRAPH-798F}) missing from current font.

/home/meuser/tmpbug.py:23: UserWarning: Glyph 24184 (\N{CJK UNIFIED IDEOGRAPH-5E78}) missing from current font.

/home/meuser/tmpbug.py:23: UserWarning: Glyph 31119 (\N{CJK UNIFIED IDEOGRAPH-798F}) missing from current font.

/home/meuser/tmpbug.py:24: UserWarning: Glyph 24184 (\N{CJK UNIFIED IDEOGRAPH-5E78}) missing from current font.
  print(plt.__version__)
/home/meuser/tmpbug.py:24: UserWarning: Glyph 31119 (\N{CJK UNIFIED IDEOGRAPH-798F}) missing from current font.
  print(plt.__version__)
3.5.0

How can I get all my  labels to show in one legend?
If this is not possible, why not?

A: Looking this problem up, I found this answer here that uses pyplotz. I adapted it to your problem and it seems to be solving your issue:
!pip install pyplotz
import matplotlib.pyplot as plt
import matplotlib

from pyplotz.pyplotz import PyplotZ
pltz = PyplotZ()
pltz.enable_chinese()

fig,ax= plt.subplots(1)
ax.plot(1,1,'.',label='english')
ax.plot(1,2,'.',label='Glück')
ax.plot(1,1,'.',label='доход')
ax.plot(1,1,'.',label='幸福')

pltz.legend()

And the output gives:

This was tested on google colab with matplotlib 3.2.2 and 3.5.0
EDIT:
Here is a way to create two legends one for the chinese characters and the second one for the other languages. Here is the code:
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import font_manager
from pyplotz.pyplotz import PyplotZ
pltz = PyplotZ()
pltz.enable_chinese()

fig,ax= plt.subplots(1)

e,=ax.plot(1,1,'.',label='english')
g,=ax.plot(1,2,'.',label='Glück')
r,=ax.plot(1,1,'.',label='доход')
c,=ax.plot(1,1,'.',label='幸福')
legend=plt.legend([e,g,r],['english','Glück','доход'],loc='best',bbox_to_anchor=(0.5, 0., 0.5, 0.5),frameon=False)
legend1=pltz.legend([c],['幸福'],loc='best',bbox_to_anchor=(0.452, -0.21, 0.5, 0.5),frameon=False)
plt.gca().add_artist(legend)

And the output gives:


text:
Q: on mountain vs at mountain
Now we were on/at Mt. Fuji, climbing up and up.

What would be the difference between choosing on or at here?

A: "At" refers to the general location of something, including the area right around it. So if you are "at the school", you might be in the parking lot across the street from it.
Other prepositions, including "on", are more precise.
So if you're at Mt. Fuji, you could be somewhere near the base. But if you're "on" Mt. Fuji, it necessarily means you're somewhere on the mountain itself.


text:
Q: MultipartFormDataStreamProvider and reading file immediately after its uploaded fails sometimes I have some Web API code that I've assembled from SO posts and other sites. However, the Task stuff is still new to me. I'm trying to copy an uploaded file to a new location, but sometimes (not all the time) I get an exception while trying to copy the file. The exception indicates that the file is in use by another process. It doesn't happen every time, though. I think I need to move the copy operation somewhere else. Here's my code. Any suggestions?
var provider = new MultipartFormDataStreamProvider(uploadroot);
                var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);

                    var docConversionId = Guid.NewGuid().ToString("N");
                    var sourceFilePath = Path.Combine(uploadroot, provider.FileData.First().LocalFileName);
                    var destinationFilePath = Path.Combine(inboxroot, docConversionId);

                    File.Copy(sourceFilePath, destinationFilePath);

                    var response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Content = new StringContent(docConversionId);
                    //response.Content.Headers.Add("DocumentConversionId", docConversionId);
                    return response;
                });
                return task;

A: You could be hitting a known issue with trying to read/delete the file immediately after you use ReadAsMultipartAsync.
Following is the bug related to it(you can take a look the resolution information for more details as to why its happening and also a workaround):
https://aspnetwebstack.codeplex.com/workitem/176

A: Since the original discussion in codeplex is dead, I'm pasting here the original explanation and workaround when the issue was originally closed back in 2013:

We are closing this issue because the root cause was found to be in
  framework code. A separate bug has been opened against an external
  partner team, and this issue will be tracked there.
The changeset:
  http://aspnetwebstack.codeplex.com/SourceControl/changeset/changes/452b8e1dfa40
reverts an attempted fix where we used FileOptions.WriteThrough to
  ensure it was not a race between the File Cache and FileStream code.
  But WriteThrough did not address the core bug and caused a performance
  degradation.
Impact on user code is this: if you upload a file with
  MultipartFormDataContent and read it on the server using
  MultiPartDataStreamProvider, the underlying file on the server may not
  be fully closed after the ReadAsMultipartAsync completes. There is a
  small window where native code may still be releasing file resources
  on another thread.
The impact is that a File.Delete or File.OpenRead done on that file
  immediately after the async read may fail with an IOException ("file
  is in use by another process"). We observed about 0.3% failure rate in
  high-load situations. The only known work-around is to put a try/catch
  around those operations, delay a short time if an IOException occurs,
  and retry. A 50ms delay generally works, but allowing for multiple
  retries is recommended. This allows the native thread to finish
  releasing its resources. In our stress labs, this
  catch-delay-and-retry algorithm always succeeds.

A: I had this crasy problem and found out that it works with await keyword.
await Request.Content.ReadAsMultipartAsync(streamProvider);

without saving a Task in a variable.


text:
Q: Building an RPM from a 3rd Party Binary Package We are switching over to using puppet for configuration management of our Linux based systems.  We have several 3rd party packages which contain custom binary installers (think JDK) and are using RPM to build them into local-only non-distributed packages.  One troublesome package has an install process which requires the following:
a) Untar binary package into install directory X.
b) Run "installer" which prompts for license acceptance and then modifies/embeds the install directory path into many subsequent scripts in the install directory.
I'm having problems defining a spec file to install this package.  For starters, in %install I handle step a and then run the installer from step b.  This installs the package into $RPM_BUILD_ROOT as expected.  However the package scripts are all embedded with $RPM_BUILD_ROOT/ rather than just  which breaks the scripts embedded with the install directory.  Is there a way to run this installer as if it were in a chroot environment or some other alternative here?  Any help appreciated.

A: Under Fedora (and I suspect also RHEL/CentOS) there is mock for exactly the type of task you describe. It is for building packages, but the "populate the chroot" part should be easy to (mis)use to create the environment you need.


text:
Q: Parse.com PHP SDK - Refresh user data - Fetch command I'm using the Parse.com PHP SDK on one of my pages. I seem to have a similar problem I faced on the iOS version but I easily solved that using the 'fetch' command.
The problem is when I edit information in my database, it does not update on my web page when I refresh the page. The user has to log out then log back in for the new data to be shown.
Here is how I'm getting the data:
<?php $u1=ParseUser::getCurrentUser()->get("auto"); echo $u1; ?>

Here is the documentation on the 'fetch' command but I don't understand how it works or how it is implemented: http://parseplatform.org/parse-php-sdk/classes/Parse.ParseUser.html#method_fetch
Does anyone know how to show the updated string values using this command or anything similar that would work?

A: The issue you're seeing is a cached object in your current session, specifically the current ParseUser. You can see that the php sdk attempts to find the current user from a variety of places, all effectively independent of the server-side copy.
You were in the right direction, you can use the fetch method to 'refresh' any ParseObject by updating it with any new changes from the database:
// get the current user
$user = ParseUser::getCurrentUser();

// fetch changes from parse
$user->fetch();

// get your newly set key/value pair
$isAuto = $user->get('auto');

Your user object will then be refreshed with the changes you need.


text:
Q: Create linked lists of string arrays I want to display the contents of an array of linked lists. Each linked list contains a String array. The content of the array of linked lists is displaying as [[[Ljava.lang.String;@15db9742], [[Ljava.lang.String;@6d06d69c], [[Ljava.lang.String;@7852e922]]. How do I solve this?
public class LinkedListOfStringArrays {
    public static void main(String[] args) {
        LinkedList<String[]> Values[] = new LinkedList[3];
        for (int i = 0; i < 3; i++){
            Values[i] = new LinkedList<String[]>();
        }
        String[] first = {"first element", "ABC"};
        String[] second = {"second element", "DEF"};
        String[] third = {"third element", "GHI"};
        Values[0].add(first);
        Values[1].add(second);
        Values[2].add(third);
        System.out.println(Arrays.toString(Values));
    }
}

A: You will have to loop through the lists and output it manually:
// Loop through the Array of LinkedLists
for(LinkedList<String[]> list : Values) {

    // Next loop through each of the lists
    for(String[] keyValuePair : list) {

        // Then output the values as you see fit
        System.out.println(keyValuePair[0] + " - " + keyValuePair[1]);
    }
}

This will give you the following output:
first element - ABC
second element - DEF
third element - GHI

A: In Java 8 you can try as
Stream.of(Values).
flatMap(list -> list.stream()).
forEach(values -> System.out.println(String.join("-",values)));


text:
Q: Cannot load json file in python I got a file of twitter streaming data in json. Now I'm trying to load it in python:
import json

tweets_data=[]
tweets_file=open('test1.txt',"r")
for line in tweets_file:
    try:
        tweet=json.load(line)
        tweets_data.append(tweet)
    except:
        continue

print(len(tweets_data))

The result is always 0. If "try" and "except" are removed, then error is "ValueError: Expecting value: line 2 column 1 (char 1)". However, each line of the file is a valid JSON according to online validator.
Here is a segment of test1.txt:
{"created_at":"Fri Jul 24 16:35:22 +0000 2015","id":624618886277640192,"id_str":"624618886277640192","text":"RT @nodenow: Essential Steps: Long Term Support for Node.js\nhttp:\/\/t.co\/MzPfvenwtT\n+1 micshasan #javascript","source":"\u003ca href=\"http:\/\/twitter.com\/download\/android\" rel=\"nofollow\"\u003eTwitter for Android\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":3290861609,"id_str":"3290861609","name":"Rajiin","screen_name":"Rajiin_07","location":"Pokhara city","url":"http:\/\/www.pokharacity.com","description":null,"protected":false,"verified":false,"followers_count":1101,"friends_count":1119,"listed_count":155,"favourites_count":2048,"statuses_count":5498,"created_at":"Wed May 20 04:58:23 +0000 2015","utc_offset":-25200,"time_zone":"Pacific Time (US & Canada)","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"000000","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"4A913C","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/617620457336893440\/3HTEKnMx_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/617620457336893440\/3HTEKnMx_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/3290861609\/1435854327","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Fri Jul 24 16:33:04 +0000 2015","id":624618308050915328,"id_str":"624618308050915328","text":"Essential Steps: Long Term Support for Node.js\nhttp:\/\/t.co\/MzPfvenwtT\n+1 micshasan #javascript","source":"\u003ca href=\"http:\/\/ifttt.com\" rel=\"nofollow\"\u003eIFTTT\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":3243544179,"id_str":"3243544179","name":"Javascript Digest","screen_name":"nodenow","location":"","url":null,"description":null,"protected":false,"verified":false,"followers_count":1238,"friends_count":1,"listed_count":1148,"favourites_count":2,"statuses_count":130923,"created_at":"Sat May 09 15:45:13 +0000 2015","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/597066594334941184\/Xe4tTtU8_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/597066594334941184\/Xe4tTtU8_normal.jpg","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":1,"favorite_count":0,"entities":{"hashtags":[{"text":"javascript","indices":[83,94]}],"trends":[],"urls":[{"url":"http:\/\/t.co\/MzPfvenwtT","expanded_url":"http:\/\/bit.ly\/1LH81ly","display_url":"bit.ly\/1LH81ly","indices":[47,69]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"javascript","indices":[96,107]}],"trends":[],"urls":[{"url":"http:\/\/t.co\/MzPfvenwtT","expanded_url":"http:\/\/bit.ly\/1LH81ly","display_url":"bit.ly\/1LH81ly","indices":[60,82]}],"user_mentions":[{"screen_name":"nodenow","name":"Javascript Digest","id":3243544179,"id_str":"3243544179","indices":[3,11]}],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en","timestamp_ms":"1437755722003"}

{"created_at":"Fri Jul 24 16:35:22 +0000 2015","id":624618888387432449,"id_str":"624618888387432449","text":"python \u041c\u043e\u0441\u043a\u0432\u0430  http:\/\/t.co\/itYJmgVvgD","source":"\u003ca href=\"http:\/\/gdepraktika.ru\" rel=\"nofollow\"\u003egdepraktika-trfnslator\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":623605809,"id_str":"623605809","name":"\u0413\u0434\u0435 \u043f\u0440\u0430\u043a\u0442\u0438\u043a\u0430?","screen_name":"gdepraktika","location":"\u0420\u043e\u0441\u0441\u0438\u044f","url":"http:\/\/gdepraktika.ru","description":"\u041f\u0440\u0430\u043a\u0442\u0438\u043a\u0430, \u0441\u0442\u0430\u0436\u0438\u0440\u043e\u0432\u043a\u0430, \u0440\u0430\u0431\u043e\u0442\u0430 \u0434\u043b\u044f \u0441\u0442\u0443\u0434\u0435\u043d\u0442\u043e\u0432, \u043e\u0431\u0443\u0447\u0435\u043d\u0438\u0435 \u0432 \u043a\u043e\u043c\u043f\u0430\u043d\u0438\u044f\u0445","protected":false,"verified":false,"followers_count":17,"friends_count":9,"listed_count":0,"favourites_count":0,"statuses_count":902069,"created_at":"Sun Jul 01 07:53:36 +0000 2012","utc_offset":10800,"time_zone":"Moscow","geo_enabled":false,"lang":"ru","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/378800000420815111\/bba61a6dcd4272794a4af41dd8a44cf5_normal.png","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/378800000420815111\/bba61a6dcd4272794a4af41dd8a44cf5_normal.png","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"trends":[],"urls":[{"url":"http:\/\/t.co\/itYJmgVvgD","expanded_url":"http:\/\/bit.ly\/1GqpqOg","display_url":"bit.ly\/1GqpqOg","indices":[15,37]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"und","timestamp_ms":"1437755722506"}

A: This is happening because there are two blank lines between the valid json lines. Just add a check for blank lines and you should be good to go.
import json
tweets_data = []
notParsed = []
tweets_file = open('test1.txt',"r")
for line in tweets_file:
    if line.strip():
        try:
            tweet=json.load(line)
            tweets_data.append(tweet)
        except:
            notParsed.append(line)
            continue
print(len(tweets_data))
print('Could not parse: ', len(notParsed))

This isn't required and I'm just revising Python because of your answer, but you could edit your code as follows:
map(json.loads, [x for x in open('test1.txt').read().split('\n') if x.strip()])

A: Two things.  First, your segment doesn't look like valid json after all.  (And copy-pasting it into the validator http://jsonlint.com confirms that.  Syntatically, there needs to be a comma between the two tweets, and the reason is that they need to be elements in some higher-level data structure (the json-equivalent of a python list == an "array," or the json-equivalent of a dict, an "object").  There can be only one root element in a json file.  See this prior question: How to read a JSON file containing multiple root elements?.
Second, if you're trying to just get ordinary access to the json data structure, and aren't trying to do anything special that depends on the notion of a line (or worrying about memory management, etc.), then you don't really need to read it in line by line like this.  Instead, you can just bind the whole shebang to a variable, and it will turn the json into nested lists and dicts according to the obvious syntax (i.e., the json curlybraces/brackets function the same as the python ones).
So once you get the json valid, the code can be as simple as:
import json
with open('test1.txt') as json_file:
  myjson = json.load(json_file)

then just access every element in the json via list indexes/dict keys.
This method ignores whitespace, so you should have no problem with the line breaks.
Ultimately, this suggests that the solution is to wrap your tweets in a top-level list ("array") and stick commas between them (maybe with regexes as a string operation?), then just access them by list indexing rather than going line by line.

A: a line may has \r \n space .etc
and you should use json.loads()
import json

tweets_data=[]
tweets_file=open('test1.txt',"r")
for line in tweets_file:
    try:
        tweet=json.loads(line.strip())
        tweets_data.append(tweet)
    except:
        continue

print(len(tweets_data))


text:
Q: How to fix Camera2 front face camera portrait video captured resulted rotated inverted I am making record video app. for video recording i am following google video recording example. Rear camera resulted perfect video but when i tried to capture video with Front camera it gives inverted video result. how i can fix this problem.in some device it's camera preview also shown inverted.
here is the code of camera setup
 private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
    private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();
private static final SparseIntArray DEFAULT_ORIENTATIONS = new SparseIntArray();

static {
    INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
    INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
    INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
    INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
}

static {
    DEFAULT_ORIENTATIONS.append(Surface.ROTATION_90, 0);
    DEFAULT_ORIENTATIONS.append(Surface.ROTATION_0, 90);
    DEFAULT_ORIENTATIONS.append(Surface.ROTATION_270, 180);
    DEFAULT_ORIENTATIONS.append(Surface.ROTATION_180, 270);
}

private void openCamera(int width, int height) {
        final Activity activity = this;
        if (null == activity || activity.isFinishing()) {
            return;
        }
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
            Log.d(TAG, "tryAcquire");
            if (!mCameraOpenCloseLock.tryAcquire(3500, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Time out waiting to lock camera opening.");
            }
            /**
             * default front camera will activate
             */
        String cameraId = manager.getCameraIdList()[0];

        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics
                .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        if (map == null) {
            throw new RuntimeException("Cannot get available preview/video sizes");
        }
        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));
        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                width, height, mVideoSize);

        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        configureTransform(width, height);
        mMediaRecorder = new MediaRecorder();
        if (ActivityCompat.checkSelfPermission(BaseActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            requestPermission();
            return;
        }
        manager.openCamera(cameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        Log.e(TAG, "openCamera: Cannot access the camera.");
    } catch (NullPointerException e) {
        Log.e(TAG, "Camera2API is not supported on the device.");
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.");
    }
}


text:
Q: If there exists a function that maps A onto B , show that A is also uncountable Let $A$ and $B$ be sets and suppose $B$ is uncountable.If there exists a function that maps $A$ onto $B$ , show that $A$ is also uncountable.
My attempt is proof by contradiction. Suppose A is countable. Then there exists a function $$h:\mathbb{N} \rightarrow A$$ where $h$ is one-to-one correspondence. Since a function maps A onto B, say $f$, then $$f:A \rightarrow B$$ is onto. Let $$g:\mathbb{N} \rightarrow B$$ Then $g(x)=f(h(x))$ . Then $g$ is onto since $f$ and $h$ are onto. Then I stuck here.

A: Your strategy is good, but ideally you would want the function $f$ to be a one-to-one correspondence. You can extract one from the function you already have with this lemma:
Lemma. If $f:A \to B$ is onto, then there exists a one-to-one correspondence $f':A'\to B$ for some $A' \subseteq A$.
Proof. Let $\leq_A$ be a total ordering on $A$ and for any $b \in B$, let $A(b)$ be the minimum element $a \in A$ (with respect to $\leq_A$) such that $f(a) = b$. Then let $A' = \{A(b) \mid b \in B\}$ and the function $f'$ equivalent to $f$ defined only on $A'$ is a one-to-one correspondence from $A'$ to $B$.

A: Here is an elaboration on my comment.
Suppose, for contradiction, that $A$ is countable, and define $g:\mathbb{N}\to B$ as you have. Since $g$ is surjective, the inverse image $g^{-1}(x)$ is nonempty for each $x\in B$, and so has a least element $a(x)$.
Let $S\subset \mathbb{N}$ be the image of $a$. We have:

*

*$a: B\to S$ is surjective, by construction;

*$a$ is injective. Indeed, if $a(x)=a(y)$, then $x=g(a(x))=g(a(y))=y$.

Therefore $a$ is a bijection between $B$ and $S$. Since $S$ is countable, $B$ must be as well, a contradiction.
The above assumes you've shown that a subset of $\mathbb{N}$ is countable; if you haven't and need help proving this lemma let me know.


text:
Q: Prove that the tangent planes at a point of a smooth surface are the same Let $z=f(x,y)$, $y=g(x,z)$, and $x=h(y,z)$ be continously differentiable functions that can be derived from an implicit function $F(x,y,z)=0$. Each of these functions define a surface and, at a point $\mathbf a=(a_1,a_2,a_3)$, the corresponding tangent planes to these surfaces can be found as follows:
$$z-a_3=[Df(a_1,a_2)]\begin{bmatrix} x-a_1 \\ y-a_2\end{bmatrix} \\ y-a_2=[Dg(a_1,a_3)]\begin{bmatrix} x-a_1 \\ z-a_3\end{bmatrix} \\x-a_1=[Dh(a_2,a_3)]\begin{bmatrix} y-a_2 \\ z-a_3\end{bmatrix}$$
Following this answer, we can express these tangent planes in the $\vec n \cdot \vec x=\vec n \cdot \vec p$ form as below:
$$\begin{bmatrix} D_1f(a_1,a_2) \\ D_2f(a_1,a_2) \\ -1 \end{bmatrix} \cdot \begin{bmatrix} x \\ y \\ z \end{bmatrix}=\begin{bmatrix} D_1f(a_1,a_2) \\ D_2f(a_1,a_2) \\ -1 \end{bmatrix} \cdot \begin{bmatrix} a_1 \\ a_2 \\ a_3 \end{bmatrix}$$
$$\begin{bmatrix} D_1g(a_1,a_3) \\ -1\\D_3g(a_1,a_3) \end{bmatrix} \cdot \begin{bmatrix} x \\ y \\ z \end{bmatrix}=\begin{bmatrix} D_1g(a_1,a_3) \\ -1\\D_3g(a_1,a_3) \end{bmatrix} \cdot \begin{bmatrix} a_1 \\ a_2 \\ a_3 \end{bmatrix}$$
$$\begin{bmatrix} -1 \\ D_2h(a_2,a_3) \\ D_3h(a_2,a_3) \end{bmatrix} \cdot \begin{bmatrix} x \\ y \\ z \end{bmatrix}=\begin{bmatrix} -1 \\ D_2h(a_2,a_3) \\ D_3h(a_2,a_3) \end{bmatrix} \cdot \begin{bmatrix} a_1 \\ a_2 \\ a_3 \end{bmatrix}$$
where $D_n$ denotes the $n$th directional derivative. How can I show that above equations actually define the same plane?
EDIT:
If first and second planes are the same, then there is the following relation between them (as Thomas stated):
$$\begin{bmatrix} D_1f(a_1,a_2) \\ D_2f(a_1,a_2) \\ -1 \end{bmatrix}=k\begin{bmatrix} D_1g(a_1,a_3) \\ -1\\D_3g(a_1,a_3) \end{bmatrix}$$
We can find a relation between them using implicit function theorem. According to this theorem, if $F(x,y,f(x,y))=0$, then $Df(a_1,a_2)=-[D_1F(\mathbf a) \; D_2F(\mathbf a)]^{-1}[D_3F(\mathbf a)]$. Thus, $D_1f(a_1,a_2)=-[D_1F(\mathbf a) \; D_2F(\mathbf a)]^{-1}[D_3F(\mathbf a)]\vec e_1$ where $\vec e_1$ is the direction towards $x$.  I don't know how to construct other relations using implicit function theorem. I know these notations are odd but any help will be appreciated.

A: The normal to a tangent plane is, up to sign, unique, if you are working in a codimension $1$ case. So if you can show that the planes have the same normal or the normal differs only by a nonzero (positive or negative) factor, then the planes coincide. If two normal vectors are linearly independent (as in your example) the planes do not coincide.


text:
Q: one letter FOR ALL BUT different color I want each Cell value starts with a letter A,B,C... to be colored a certain color.
I can do that only if it says only A it works.
What needs to be fixed?
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Left(Target.Value, 1) = "A" Then Target.Interior.Color = 34
If Left(Target.Value, 1) = "B" Then Target.Interior.Color = 36
If Left(Target.Value, 1) = "C" Then Target.Interior.Color = 39
If Left(Target.Value, 1) = "D" Then Target.Interior.Color = 41
If Left(Target.Value, 1) = "E" Then Target.Interior.Color = 38
If Left(Target.Value, 1) = "F" Then Target.Interior.Color = 37
If Left(Target.Value, 1) = "G" Then Target.Interior.Color = 35

End Sub

A: your macro works but colors are same. use interior.colorindex property
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   If Left(Target.Value, 1) = "A" Then Target.Interior.ColorIndex = 1
   If Left(Target.Value, 1) = "B" Then Target.Interior.ColorIndex = 2
   If Left(Target.Value, 1) = "C" Then Target.Interior.ColorIndex = 3
   If Left(Target.Value, 1) = "D" Then Target.Interior.ColorIndex = 4
   If Left(Target.Value, 1) = "E" Then Target.Interior.ColorIndex = 5
   If Left(Target.Value, 1) = "F" Then Target.Interior.ColorIndex = 6
   If Left(Target.Value, 1) = "G" Then Target.Interior.ColorIndex = 7
End Sub

there u have palete


text:
Q: Migration Angular 5 to 6 - 'ng update' hanging and do nothing I'm migration Angular from 5 to 6.
After added latest angular-cli to my project i try to execute 'ng update'.
But absolutely nothing happens (the console hangs and i have to cancel it).
ng version:
Angular CLI: 6.0.8
Node: 8.9.3
OS: win32 x64
Angular: 6.0.4
... animations, common, compiler, compiler-cli, core, forms
... http, platform-browser, platform-browser-dynamic
... platform-server, router

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.6.8
@angular-devkit/core         0.6.8
@angular-devkit/schematics   0.6.8
@angular/cli                 6.0.8
@schematics/angular          0.6.8
@schematics/update           0.6.8
rxjs                         6.2.0
typescript                   2.9.1
webpack                      3.12.0

Does somebody had the same issue?

A: Have you done the following (in this sequence!):

*

*Install Angular/CLI 6 global: npm install -g @angular/cli

*Install Angular/CLI 6 local:  npm install @angular/cli

*Install dependent packages for Angular/CLI 6:  ng update @angular/cli

*Install dependent packages for angular/core 6:  ng update @angular/core

*Install anything else: npm install
Next, check and see if it works.  I use ng build --prod.  That command shakes the tree pretty hard.


text:
Q: How to change drupal password on localhost (xampp)? I have a Drupal website on my computer.
I forgot its password and I don't know how to recover it.
I can't send emails in my computer or localhost.
I read a lot of webpages about resetting the password in Drupal on localhost, but not working.

A: To reset you password use this command:
UPDATE users SET pass='$S$Cd059Vsxc8berFeg6hspaa7ejx2bSxyUisvCbT4h9o8XIgSUtPKz' WHERE uid=1;

This password is: password
To sent emails from XAMPP, use SMTP module: https://www.drupal.org/project/smtp

A: Just create a file "new_password.php" (or with any other name) inside your drupal folder and access it using browser. It will generate one way encrypted hash password for you.
<?php
  define("DRUPAL_ROOT", getcwd());
  require_once DRUPAL_ROOT . "/includes/bootstrap.inc";
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  require_once "includes/password.inc";
  echo user_hash_password("123456");
  die();
  menu_execute_active_handler();
?>
When you run this code in browser it will show you hash password like
$S$D95YW4EejaUDPq5nZ7Z2Ljx1Ud4wlN1iTMQdAKton70JcQpCZmrG
Now you need to update your database table using above hash. Open your database using PHPMyAdmin or Workbench and run the below query.
UPDATE users SET pass = '$S$D95YW4EejaUDPq5nZ7Z2Ljx1Ud4wlN1iTMQdAKton70JcQpCZmrG' WHERE uid = 1;
Now you can access drupal using username as "admin" and password as "123456". Make sure you update password after login to the admin.

A: You can reset the localhost password using the drush
drush upwd --password="yourpassword" username
for eg: drush upwd --password="sweety" pragya

A: There is one more way to reset password using drush .
 Just type
drush uli.
This will give you one time password reset url for Admin.
Something like http://default/user/reset/1/1428579639/O1Rs12HxYZV7rrMUR7xuXhg9RDvsk9OFZ1-nVCoSVWU
Replace default with your actual drupal URL and paste it in browser it will ask for new password.


text:
Q: python: merging dictionaries by identical value of key I am new to python and have looked at other answers on merging dictionaries but was still a bit confused.
I am looking to merge together two dictionaries in python by a common value within a specific key to output that common key with the other keys from both dictionaries in a new dictionary.
Here is sample data:
add_sal = {'career_medicine': None, 'career_law': None, 'median_salary': None, 'mean_salary': 75000.0, 'career_business': 'operations / logistics', 'number': None}

add_perc = {'percent': 0.07, 'career_business': 'operations / logistics'}

I would like to merge on the key value pair of 'career_business': 'operations / logistics'
and output a dictionary that looks like this:
add_all = {'career_medicine': None, 'career_law': None, 'median_salary': None, 'mean_salary': 75000.0, 'career_business': 'operations / logistics', 'number': None, 'percent': 0.07}

An additional problem is that I do not know if the names will match, and I am looping through a list of add_sal and a list of add_perc.
Any advice would be appreciated!
Thank you in advance!

A: What you asked for is simply enough done:

import copy
if 'career_business' in add_sal and 'career_business' in add_perc and \
      add_sal['career_business'] == add_perc['career_business']:
   add_all = copy.deepcopy( add_sal )
   add_all['percent'] = add_perc['percent']

However, your data structure seems rather odd for the kind of data you seem to have.  You don't say what problem you're trying to solve with it, but your choice of a dictionary with random looking things in it seems likely to be at the root of your problems.  Maybe you wanted  something more like a dictionary keyed by the career name, like:

career_sal[ 'operations / logistics' ] = 75000.0

and corresponding stuff for the other pieces.


text:
Q: Открытие файла из локальной сети Я из командной строки windows запускаю файл реестра так:
>regedit /s C:\file.reg

Как мне запустить этот файл если он находиться в локальной сети? например по адресу //comp/folder/file.reg или //172.31.200.200/folder/file.reg
или можно сделать bat файл, но чтобы также запускать его из командной строки.
A: При доступе к компьютеру в локальной сети используется \\NAME_OR_IP а не //NAME_OR_IP.
Команда выглядит вот так:
regedit /s \\COMP\Folder\file.reg
regedit /s \\172.31.200.200\Folder\file.reg


text:
Q: How to unit test validation message in Angular template driven forms I have a very basic Angular template driven form with a single  field which is required. A validation message is displayed if the field is invalid, which is the case when the component is first loaded as the field is required but empty. The code runs as expected when viewed in the application and the validation message is displayed.
When testing the component via a Jasmine unit test the validation message is not picked up and the test fails.
I am confident that the logic to look for the validation message is working, because if I remove the *ngIf directive on the message DIV then the test passes.
I have tried the following:

*

*importing the BrowserModule into the test spec

*running the test within a fakeAsync() block

Template:
<form #form="ngForm">

  First name:

  <input #firstName="ngModel"
    type="text"
    name="firstName"
    [(ngModel)]="firstNameText"
    required />

      Please enter a valid first name

</form>

Component class:
import { Component } from '@angular/core';

@Component({
  selector: 'app-person-form',
  templateUrl: './person-form.component.html'
})
export class PersonFormComponent  {
  public firstNameText: string;
}

Jasmine test spec:
import { ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
import { PersonFormComponent } from './person-form.component';
import { FormsModule } from '@angular/forms';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';

describe('PersonFormComponent', () => {
  let fixture: ComponentFixture<PersonFormComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule ],
      declarations: [ PersonFormComponent ]
    });

    fixture = TestBed.createComponent(PersonFormComponent);
    fixture.detectChanges();
  });

  it('should show a validation error if the first name was touched but left empty', () => {
    let firstNameValidationError: DebugElement;

    // try to get a handle to the validation message (should exist as form is invalid):
    firstNameValidationError = fixture.debugElement.query(By.css('.validation-error'));

    // the validation error should be found:
    expect(firstNameValidationError).toBeTruthy();
  });
});

A: Component initialization should always be done in a async block
beforeEach(async() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule ],
      declarations: [ PersonFormComponent ]
    });

    fixture = TestBed.createComponent(PersonFormComponent);
    fixture.detectChanges();
});

Also you may need to run change detection once again after the component is initialised
it('should show a validation error if the first name was touched but left empty', () => {
    let firstNameValidationError: DebugElement;

    fixture.detectChanges(); // run change detection
    firstNameValidationError = fixture.debugElement.query(By.css('.validation-error'));

    // the validation error should be found:
    expect(firstNameValidationError).toBeTruthy();
});

A: The complete revised test is as follows, thanks to Amit Chigadani for solving this:
import { ComponentFixture, TestBed, fakeAsync } from '@angular/core/testing';
import { PersonFormComponent } from './person-form.component';
import { FormsModule } from '@angular/forms';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';

describe('PersonFormComponent', () => {
  let fixture: ComponentFixture<PersonFormComponent>;

  beforeEach(async() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule ],
      declarations: [ PersonFormComponent ]
    });

    fixture = TestBed.createComponent(PersonFormComponent);
    fixture.detectChanges();
  });

  it('should show a validation error if the first name was touched but left empty', () => {
    let firstNameValidationError: DebugElement;
    fixture.detectChanges(); // run change detection

    // try to get a handle to the validation message (should exist as form is invalid):
    firstNameValidationError = fixture.debugElement.query(By.css('.validation-error'));

    // the validation error should be found:
    expect(firstNameValidationError).toBeTruthy();
  });
});

A: Add these lines at the beginning of the test
 let component = fixture.componentInstance;
    component.firstNameText = '';
    fixture.detectChanges();

and after this, set some name to the firstNameText as below
component.firstNameText = 'test';

At this point, you should expect the error to be falsy.


text:
Q: Get the column name of list I tried this:
var fieldValues = currentItem.get_fieldValues();

But it returns [object object]. How can I see through this without know the column name?

A: You can use below script.
var fieldValues = currentItem.get_fieldValues();

console.log(JSON.stringify(fieldValues));

Once script is executed second statement will print the data in console in readable format.


text:
Q: How to hide subfolder of static pages in Wordpress using htaccess I need help please because I cannot find a solution for my problem.
I need to hide a subfolder in the url of my wordpress site.
I created a subfolder where I uploaded some static pages in php
Example: domain.com/subfolder/file.php
What I need is remove/hide "subfolder" to get the next:
domain.com/file.php
I tried many htaccess codes I found here but I always get a 404 error.
Thanks in advance for your help.


text:
Q: Python Pandas ValueError: Can only compare identically-labeled DataFrame objects I was trying to learn pandas, but in line 21 it gave an error. Please help me to solve this problem.
import pandas as pd
import numpy as np

data = np.random.randint(10,100,75).reshape(15,5)
df = pd.DataFrame(data, columns= ["Column1","Column2","Column3","Column4","Column5",])
result = df
result = df.columns # kolonları liste şeklinde bize döndürür. Index(['Column1', 'Column2', 'Column3', 'Column4', 'Column5'], dtype='object')
result = df.head(10) # ilk 10 satırın kayıtları gelir. Eğer sayı girmezsek ilk 5 satırı getirir.
result = df.tail(10) # Son 10 satırın kayıları gelir. Eğer sayı girmezsek son 5 satırı getirir.
result = df["Column1"].head() # Kolon 1' in ilk 5 satırını getirir.
result = df.Column1.head()# Yukarıdaki kodla aynı işlemi yapar.
result = df[["Column1","Column2"]].tail() # kolon 1 ve kolon 2' nin son 5 kayıtlarını getirir.
result = df[5:15][["Column1","Column2"]].head()# 5 ile 9. satırlar arasını alır.
result = df > 50 # True ve False lardan oluşan bir dataframe oluşturur.
result = df[df>50] # Koşulu sağlayan değerleri döndürür. Olmayanları ise NaN olarak döndürür.
result = df[df %2 == 0]
result = df["Column1"] > 50 # Sadece kolon 1 için koşulları kontrol eder.
result = df[df["Column1"] > 50][["Column1","Column2"]]
result = df[(df["Column1"] > 50) & (df["Column1"] <= 70)] # 1. kolon için 50 ve 70 arasındaki değerler gelir.
result = df[(df["Column1"] > 50) | (df["Column1"] <= 70)] # 1. kolon için 50 veya 70 arasındaki değerler gelir.
result == df.query("Column1 >= 50 & Column1 %2 == 0")

print(result)

A: You are trying to compere result with the dataframe. Correct is:
result = df.query("Column1 >= 50 & Column1 %2 == 0")


text:
Q: determine if output is string or integer I am trying to write a script which connects to a database then run a query that returns count of rows in a table. sometimes database or table have problems and instead of an integer they return an error. for example:
A database connection does not exist
i want to determine if output is the integer i want or its an error. i searched through various posts but none of them worked in my script. what should i do?
DB2PATH=/bin/db2
$DB2PATH connect to $1 >> /dev/null
count=$($DB2PATH -x " select count(*) from TEST122 ")

if ! [[ "$count" =~ ^[0-9]+$ ]]
then
    echo "string"
else
    echo $count
fi

i changed the if condition in many different ways. i used -eq and -ne. it keep returning string. and the value of count is 11.
update:
printf '%s' "$count" | hexdump -c
output:
0000000                                       1   1
000000b

A: To ignore and trim leading and trailing whitespace around the number:
if [[ $count =~ ^[[:space:]]*([[:digit:]]+)[[:space:]]*$ ]]; then
  echo number
  count=${BASH_REMATCH[1]}
else
  echo other
fi

Or with standard sh syntax:
trimmed=${count#"${count%%[![:space:]]*}"}
trimmed=${trimmed%"${count##*[![:space:]]}"}
case $trimmed in
  ("" | *[![:digit:]]*) echo other;;
  (*) echo number; count=$trimmed;;
esac

A: Looks like the variable count has some extra undesirable spaces which is causing your condition to fail it to be an integer type.
You need to strip out the extra spaces in your variable to fix it. Use an external tool like xargs to remove the spaces. The useful thing with xargs is it swallows up both leading and trailing spaces in the variable.
if ! [[ $( xargs <<< "$count" ) =~ ^[0-9]+$ ]]
then
    echo "string"
else
    echo $count
fi

If not for an external tool like xargs use the parameter expansion provided by the shell itself
if ! [[ "${count// /}" =~ ^[0-9]+$ ]]
then
    echo "string"
else
    echo $count
fi

The syntax ${count// /} will replace all the spaces with an empty string and the resultant string is used in the comparison with the regular expression defined.

A: Putting negation inside expresion gives me correct results:
if [[ ! "$count" =~ ^[0-9]+$ ]]
then
    echo "string"
else
    echo $count
fi


text:
Q: Can I put constraint on column without referring to another table? I have a text column that should only have 1 of 3 possible strings. To put a constraint on it, I would have to reference another table. Can I instead put the values of the constraint directly on the column without referring to another table?

A: If this is SQL Server, Oracle, or PostgreSQL, yes, you can use a check constraint.
If it's MySQL, check constraints are recognized but not enforced. You can use an enum, though. If you need a comma-separated list, you can use a set.
However, this is generally frowned upon, since it's definitely not easy to maintain. Just best to create a lookup table and ensure referential integrity through that.

A: In addition to the CHECK constraint and ENUM data type that other mention, you could also write a trigger to enforce your desired restriction.
I don't necessarily recommend a trigger as a good solution, I'm just pointing out another option that meets your criteria of not referencing a lookup table.
My habit is to define lookup tables instead of using constraints or triggers, when the rule is simply to restrict a column to a finite set of values.  The performance impact of checking against a lookup table is no worse than using CHECK constraints or triggers, and it's a lot easier to manage when the set of values might change from time to time.
Also a common task is to query the set of permitted value, for instance to populate a form field in the user interface.  When the permitted values are in a lookup table, this is a lot easier than when they're defined in a list of literal values in a CHECK constraint or ENUM definition.

Re comment "how exactly to do lookup without id"
CREATE TABLE LookupStrings (
  string VARCHAR(20) PRIMARY KEY
);

CREATE TABLE MainTable (
  main_id INT PRIMARY KEY,
  string VARCHAR(20) NOT NULL,
  FOREIGN KEY (string) REFERENCES LookupStrings (string)
);

Now you can be assured that no value in MainTable.string is invalid, since the referential integrity prevents that.  But you don't have to join to the LookupStrings table to get the string, when you query MainTable:
SELECT main_id, string FROM MainTable;

See?  No join!  But you get the string value.

Re comment about multiple foreign key columns:
You can have two individual foreign keys, each potentially pointing to different rows in the lookup table. The foreign key column doesn't have to be named the same as the column in the referenced table.
My common example is a bug-tracking database, where a bug was reported by one user, but assigned to be fixed by a different user. Both reported_by and assigned_to are foreign keys referencing the Accounts table.
CREATE TABLE Bugs (
  bug_id INT PRIMARY KEY,
  reported_by INT NOT NULL,
  assigned_to INT,
  FOREIGN KEY (reported_by) REFERENCES Accounts (account_id),
  FOREIGN KEY (assigned_to) REFERENCES Accounts (account_id)
);

A: In Oracle, SQL Server and PostgreSQL, use CHECK constraint.
CREATE TABLE mytable (myfield INT VARCHAR(50) CHECK (myfield IN ('first', 'second', 'third'))

In MySQL, use ENUM datatype:
CREATE TABLE mytable (myfield ENUM ('first', 'second', 'third'))


text:
Q: White space on bottom of Firefox and Chrome pages I asked a few days ago about removing white space that occurred in the right of my page when altering the size of the FF and Chrome browser windows. I was helped very quickly and fixed the issue (here is the post: Minimizing browser window in Firefox & Chrome adds white space to right of page).
But the same tips don't seem to work for the white space on the bottom. Plus, it is always the same height no matter the size of the window, so I thought it was padding or margin, but it doesn't seem to be, as all the elements which would have any effect on the bottom of the page have padding and margin set to 0.
Any ideas? Relevant HTML and CSS below.

html {
 margin:0;
 padding:0;
 height:100%;
 width:100%;
 position:relative;
}

body {
 margin:0;
 padding:0;
 height:100%;
 width:100%;
 position:absolute;
 bottom:0;
 top:0;
 left:0;
 right:0;
}

p {
 margin:0;
 padding:0;
 color:#1C1C1C;
}

img {
 margin:0;
 padding:0;
}

.maincontainer {
 position:relative;
 padding:0;
 margin:0;
}

.container {
 width:100%;
 min-height:100%;
 position:relative;
 margin:0;
 padding:0;
}

.container:after {
 content:"";
 display:block;
}

.logo {
 float:left;
 margin-left:20px;
 font-family:'Advent Pro', sans-serif;
 font-weight:100;
 color:#1C1C1C;
}

@media screen and (min-width:768px) {
 .logo {
  float:left;
  margin-left:5px;
  font-family:'Advent Pro', sans-serif;
  font-weight:100;
  color:#1C1C1C;
 }
}

.name {
 float:left;
 margin:5px 10px 0px 10px;
 font-size:37px;
}

.type {
 float:left;
 width:50px;
 margin-top:6px;
 padding:1px 0px 1px 10px;
 font-size:15px;
 border-left:1px solid #1C1C1C;
}

.nav {
 float:right;
 margin:0;
 padding:0;
 list-style:none;
 width:300px;
}

@media screen and (min-width:500px) {
 .nav {
  float:right;
  margin:0;
  padding:0;
  list-style:none;
  width:444px;
 }
}

.nav li {
 float:left;
 padding:16px 10px 13px 10px;
 font-family:'Advent Pro', sans-serif;
 font-weight:200;
 font-size:17px;
 color:#1C1C1C;
}

.nav li:hover {
 border-bottom:2px solid #1C1C1C;
}

@media screen and (min-width:500px) {
 .nav li {
  float:left;
  padding:16px 25px 13px 25px;
  font-family:'Advent Pro', sans-serif;
  font-weight:200;
  font-size:17px;
  color:#1C1C1C;
 }
}

.reposition {
 position:absolute;
 left:50%;
 -webkit-transform: translate(-50%, -0%);
 -moz-transform: translate(-50%, -0%);
}

@media screen and (min-width: 768px) {
 .reposition {
  position:static;
  float:right;
  -webkit-transform: translate(-0%, -0%);
  -moz-transform: translate(-0%, -0%);
 }
}

.navbar-toggle {
 margin-top:13px;
 position:absolute;
 right:0;
}

.collapse {
 height:56px;
 width:100%;
}

.navbar-header {
 float:left;
 display:inline-block;
 height:55px;
 padding:0;
 margin:0;
}

.mainbody {
 width:100%;
 padding:0 0 20px 0;
 margin:0;
 float:left;
}

.slideshow {
 width:100%;
 margin:0;
 padding:0;
}

.fadein {
 width:100%;
 margin:0;
 padding:0;
}

.fadein img {
 width:95.9%;
 position:absolute;
 left:50%;
 -webkit-transform: translate(-50%, -0%);
 -moz-transform: translate(-50%, -0%);
 margin:0;
 padding:0;
}

@media screen and (max-width: 1025px) {
 .fadein img {
  width:96%;
  position:absolute;
  left:50%;
  -webkit-transform: translate(-50%, -0%);
  -moz-transform: translate(-50%, -0%);
  margin:0;
  padding:0;
 }
}

@media screen and (min-width: 1120px) {
 .fadein img {
  width:auto;
  height:85.8%;
  position:absolute;
  left:50%;
  -webkit-transform: translate(-50%, -0%);
  -moz-transform: translate(-50%, -0%);
  margin:0;
  padding:0;
 }
}

@media screen and (min-width: 1441px) {
 .fadein img {
  width:72.3%;
  position:absolute;
  left:50%;
  -webkit-transform: translate(-50%, -0%);
  -moz-transform: translate(-50%, -0%);
  margin:0;
  padding:0;
 }
}

.mainfooter {
 width:100%;
 height:20px;
 position:absolute;
 bottom:0;
 margin:0;
 padding:0;
 float:left;
}

.footer {
 position:relative;
 bottom:1px;
 float:right;
 width:100%;
 height:20px;
 padding:0 10px 0 0;
 background-color:#F8F8F8;
 border:1px solid #E7E7E7;
 margin:0;
}

.copyright {
 float:right;
 font-family: 'Advent Pro', sans-serif;
 font-weight: 100;
 font-size:12px;
 margin:0;
 padding:0;
}

@media screen and (min-width: 1441px) {
 .copyright {
  float:right;
  font-family: 'Advent Pro', sans-serif;
  font-weight: 200;
  font-size:12px;
  margin:0;
  padding:0;
 }
}

.media li {
 float:left;
 list-style:none;
 position:relative;
 right:30px;
 bottom:2px;
 margin:0 3px 0 3px;
 padding:0;
}

@media only screen and (max-width:480px) {
 .media li {
  display:none;
 }
}
<!DOCTYPE html>

Tim Corin

Wildlife Photography

         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

          Toggle navigation

         </button>

Home

Gallery

About

Contact

Blog

Copyright Tim Corin Photography 2015. All Rights Reserved.

A: Looks like the ul in the footer is pushing stuff down. Try adding:
.media {
    margin: 0;
    padding: 0;
}


text:
Q: Request Web Service to get JSON I need to hit web service URL which is giving me JSON object and use basic authentication. How can I perform the the same in JavaScript. I am using the code below, but nothing happens on browser.

<title>Hello World</title>

A: check jQuery out for this action. It would result in something like
    $.get("http://yourRestprovider.com/yourResource",function(data){
    //handle your data
    },"json");

please specify what you mean with basic authentication since I see no approach of authenticating against the server in your code snippet!

A: (You don't need JQuery for this.)
First make sure the inner function is running at all, so try setting the function to onreadystatechange instead of onload.
As for authentication: If your domain (the thing that replaces 'url of service') has the same origin as the page the script is in, and you're already doing some sort of authentication which stores a login session cookie, you don't need to do anything else.

A: Hi i am using below code : after that it just shows loading on browser.

<title>Hello World</title>


text:
Q: Using Javascript inside HTML file to read a text file in line by line and store in variables Essentially, I need to create an array of arrays.
I am using Javascript inside an .HTML file. I am reading from a .txt file
Let's call the first array "alerts" and then each array inside that is an "incident."
Each incident has three values associated with it: an ID number, a latitude value, and a longitude value.
If I put the values in a text file and each one is on a separate line, what function/how should I go about reading in each, and then assigning them to variables to be stored in an incident array?
<script type="text/javascript">

        //open text file
        $f = fopen("LatLngTest.txt", "r");
        //read line by line: 1st line=ID, 2nd line=LAT, 3rd line=LNG

        //store in ID, LAT, LNG variables

        //close text file
        fclose($f);
        //create incident array and save ID, LAT, LNG as one incident
        var incident = new Array (ID, LAT, LNG);

        //create array of alerts
        var alerts = new Array();
        //if statement to check length of array

            //and add this incident to the end
            //alerts[i] = incident;
    </script>

A: You need to give the page the text before you send it to the server, or use AJAX. I'm going to assume the easiest for you will be just dumping it onto the page:
<script>
  (function(){
    <?php echo "var fileContent = '" . file_get_contents("LatLngTest.txt") . "'," ; ?>
    alerts = fileContent.split("\n").map(function(lineItem){
       // Assuming each line is csv: ID,LAT,LNG
       // and that there are no commas in the values
       var field = lineItem.split(",");
       return {ID: field[0], LAT: field[1], LNG: fields[2]};
    });

    // now alerts looks like this: [{ID: ..., LAT: ..., LNG: ...}, {...}];

  })();
</script>


text:
Q: Почему при проверке условия только третий аргумент (arg3) проверяется на диапазон значения function getColor(arg1 = 0, arg2 = 0, arg3 = 0) {
`if( 0 < arg1 && arg2 && arg3 < 255 )` {
    if(arg1 && arg2 && arg3) {
        return 'rgb(' + arg1 + ', ' + arg2 + ', ' + arg3  + ')';
    }else if (arg1 && arg2) {
        return 'rgb(' + arg1 + ', ' + arg2 + ', ' + arg3  + ')'
    }else if (arg1) {
        return 'rgb(' + arg1 + ', ' + arg2 + ', ' + arg3  + ')';
    }else {
        return 'rgb(' + arg1 + ', ' + arg2 + ', ' + arg3  + ')';
    }
}else {
    return 'Неправильное выражение аргумента, от 0 до 255'
}
};

getColor(23, 100, 1340);

A: я бы на вашем месте написал функцию в виде
function getRGBColorString(r = 0, g = 0, b = 0){
    if( [r,g,b].some( c => c < 0 || c > 255) ){
        throw new RangeError("Неправильное выражение аргумента, от 0 до 255");
    }

    return `rgb(${r}, ${g}, ${b})`;
}

A: всего то немного логики в условии)
function getColor(arg1 = 0, arg2 = 0, arg3 = 0) {
    if((0 < arg1 && arg1 <= 255) && (0 < arg2 && arg2 <= 255) && (0 < arg3 && arg3 <= 255)) {
    if(arg1 && arg2 && arg3) {
        return 'rgb(' + arg1 + ', ' + arg2 + ', ' + arg3  + ')';
    }else if (arg1 && arg2) {
        return 'rgb(' + arg1 + ', ' + arg2 + ', ' + arg3  + ')'
    }else if (arg1) {
        return 'rgb(' + arg1 + ', ' + arg2 + ', ' + arg3  + ')';
    }else {
        return 'rgb(' + arg1 + ', ' + arg2 + ', ' + arg3  + ')';
    }
}else {
    return 'Неправильное выражение аргумента, от 0 до 255'
}
};