text:
Q: find modified files recursively and copy with directory preserving directory structure I want to find images, from a directory, that were added in last 1 year and copy them to a new directory preserving original folder structure.
I am using find but it is not copying anything. is there any way it can be done using 1 line command?
find  image/* -mtime +356 -exec cp  {} modified-last-year/ \;

I am in the image directory when running this command and i want to only search image folder recursively.
[EDIT] After the two answers I did following.
 1. find  image/* -mtime +356 | cpio -pd /target_dir
 I get 0 Blocks.

* find /full/path/to/image -mtime 365 -type f ( "-name *.jpg -o -name *.gif ) -execdir cp {} /full/path/to/image_target_dir/modified-last-year \;
AND

* find /full/path/to/image -mtime 365 -type f -execdir cp {} /full/path/to/image_target_dir/modified-last-year \;
 Nothing copied.
AND simply find to get count of files with and without -type f.

* find /full/path/to/image -mtime 365 -type f | wc -l
i get 0.
I could verify that there are indeed files with in image dir and in sub directories which were added in last 1 yr. infact there should be more than 200 images.
[EDIT 2]
I have to also exclude one directory from find so the following code worked fine.
Thanks to 1st answer, i was able to create this.

find  /full/path/to/image/* -path /full/path/to/image/ignored_dir -prune -o -print -mtime -365 | cpio -pd /full/path/to/target_dir/modified-last-year

A: You can use find and cpio in passthrough mode:
 find  image/ -mtime -365 | cpio -pd /target_dir

EDIT: removed unnecessary * from the find path.

A: If you already are in directory image, then find  image/* ... spells trouble. Instead for relative paths, either use find . (etc)  where the "." signifies the present directory and its sub-directory tree, or better yet, use absolute paths:
$ find /full/path/to/imagedir -mtime -365 -execdir cpio -pdv {} /absolute/path/to/targetdir \;

Provided you have proper permission to do so, the above should copy all files modified more recently than 365*24 hours (before today) in yr target-directory, while preserving the directory structure.
Option -execdir is safer than -exec, does the same but is executed from the directory where the selected file is found.
You can further restrict the files being parsed by find by specifying the options -type f \( "-name \*.jpg -o -name \*.gif \) in the above cmd.
cpio's options are:
-p for passthrough (does not make an archive out of the set of dound files)
-d to preserve the directory structure
-v to visualize files being copied

Look at the manual page for find, at https://www.gnu.org/software/cpio/manual/cpio.html for the complete cpio online manual, and remember www.startpage.com is a friend that does not make you the product when you look for answers.


text:
Q: Robot Frame work response timeout Need input on robot framework  response timeout,
By default robot frame gets timed by 3sec.
Is there any way to increase the response time from 3sec(default) to 10 seconds.
Thanks,
Vignesh

A: | Library | Telnet | 30 Seconds
This Command will overwrite default timeout of 3 seconds

redpajama_set_name: RedPajamaStackExchange


text:
Q: Permissions for making some some (but not all) files visible directly under a directory On wikipedia I read the following:

The read permission, which grants the ability to read a file. When set
  for a directory, this permission grants the ability to read the names
  of files in the directory (but not to find out any further information
  about them such as contents, file type, size, ownership, permissions,
  etc.)

With this, is there any way to only let people in my group see (read) the names of a subset of the files/directories I have in a directory?
E.g. if I have
A ---- B
  |
  |----C
  |
  |----D

can I modify permissions so that members of my groups can only see (read) the names C and D but not B? (if they ls A for example).
If this is not possible, what is the rationale behind it? What if I want to completely hide some files I have in  my folders? What would the "UNIX way" of dealing with this situation?

A: Short answer: No. You cannot make only some files in a directory "invisible" to those that do not belong to certain group.
Have a look at the question Why do directories need the executable (X) permission to be opened? - the subject is nicely covered there, so I won't just replicate it here. The important thing to understand is that a directory is a separate entity - just as a file - so any permissions can only affect it as a whole.


text:
Q: How do I compare characters with combining diacritic marks ɔ̃, ɛ̃ and ɑ̃ to unaccented ones in python (imported from a utf-8 encoded text file)? Summary: I want to compare  ɔ̃, ɛ̃ and ɑ̃ to ɔ, ɛ and a, which are all different, but my text file has ɔ̃, ɛ̃ and ɑ̃ written as ɔ~, ɛ~ and a~.

I wrote a script which moves along the characters in two words simultaneously, comparing them to find the pair of characters which is different The words are of equal length (excepting for the diacritic issue which introduces an extra character), and represent the IPA phonetic pronunciation of two French words only one phoneme apart.
The ultimate goal is to filter a list of anki cards so that only certain pairs of phonemes are included, because other pairs are too easy to recognize. Each pair of words represents an anki note.
For this I need to differentiate the nasal sounds ɔ̃, ɛ̃ and ɑ̃ form other sounds, as they are only really confusable with themselves.
As written, the code treats accented characters as the character plus ~, and so as two characters. Thus if the only difference in a word is between a final accented and on-accented character, the script finds no differences on the last letter and as written will then find one word shorter than the other (the other still has the ~ left) and throw an error trying to compare one more character. This is a whole 'problem' by itself, but if I can get the accented characters to read as single units the words will then have the same lengths, and it will disappear.
I do not want to replace the accented characters with non-accented ones, as some people do for comparisons, because they are different sounds.
I have tried 'normalizing' the unicode to a 'combined' form, e.g.
unicodedata.normalize('NFKC', line), but it didn't change anything.

Here is some output, including the line at which it just throws the error; the printouts show the words and character of each word that the code is comparing; the number is the index of that character within the word. The final letter is therefore what the script 'thinks' the two characters are, and it sees the same thing for ɛ̃ and ɛ. It is also choosing the wrong pair of letters then when it reports the differences, and it's important that the pair is right because I compare with a master list of allowable pairs.
0 alyʁ alɔʁ a a # this first word is done well
1 alyʁ alɔʁ l l
2 alyʁ alɔʁ y ɔ # it doesn't continue to compare the ʁ because it found the difference
...
0 ɑ̃bisjø ɑ̃bisjɔ̃ ɑ ɑ
1 ɑ̃bisjø ɑ̃bisjɔ̃ ̃ ̃  # the tildes are compared / treated  separately
2 ɑ̃bisjø ɑ̃bisjɔ̃ b b
3 ɑ̃bisjø ɑ̃bisjɔ̃ i i
4 ɑ̃bisjø ɑ̃bisjɔ̃ s s
5 ɑ̃bisjø ɑ̃bisjɔ̃ j j
6 ɑ̃bisjø ɑ̃bisjɔ̃ ø ɔ # luckily that wasn't where the difference was, this is
...
0 osi ɛ̃si o ɛ # here it should report (o, ɛ̃), not (o, ɛ)
...
0 bɛ̃ bɔ̃ b b
1 bɛ̃ bɔ̃ ɛ ɔ # an error of this type
...
0 bo ba b b
1 bo ba o a # this is working correctly
...
0 bjɛ bjɛ̃ b b
1 bjɛ bjɛ̃ j j
2 bjɛ bjɛ̃ ɛ ɛ # AND here's the money, it thinks these are the same letter, but it has also run out of characters to compare from the first word, so it throws the error below
Traceback (most recent call last):

  File "C:\Users\tchak\OneDrive\Desktop\French.py", line 42, in <module>
    letter1 = line[0][index]

IndexError: string index out of range

Here is the code:
def lens(word):
    return len(word)

# open file, and new file to write to
input_file = "./phonetics_input.txt"
output_file = "./phonetics_output.txt"
set1 = ["e", "ɛ", "œ", "ø", "ə"]
set2 = ["ø", "o", "œ", "ɔ", "ə"]
set3 = ["ə", "i", "y"]
set4 = ["u", "y", "ə"]
set5 = ["ɑ̃", "ɔ̃", "ɛ̃", "ə"]
set6 = ["a", "ə"]
vowelsets = [set1, set2, set3, set4, set5, set6]
with open(input_file, encoding="utf8") as ipf, open(output_file, encoding="utf8") as opf:
    # for line in file;
    vowelpairs= []
    acceptedvowelpairs = []
    input_lines = ipf.readlines()
    print(len(input_lines))
    for line in input_lines:
        #find word ipa transctipts
        unicodedata.normalize('NFKC', line)
        line = line.split("/")
        line.sort(key = lens)
        line = line[0:2] # the shortest two strings after splitting are the ipa words
        index = 0
        letter1 = line[0][index]
        letter2 = line[1][index]
        print(index, line[0], line[1], letter1, letter2)

        linelen = max(len(line[0]), len(line[1]))
        while letter1 == letter2:
            index += 1
            letter1 = line[0][index] # throws the error here, technically, after printing the last characters and incrementing the index one more
            letter2 = line[1][index]
            print(index, line[0], line[1], letter1, letter2)

        vowelpairs.append((letter1, letter2))

    for i in vowelpairs:
        for vowelset in vowelsets:
            if set(i).issubset(vowelset):
                acceptedvowelpairs.append(i)
    print(len(vowelpairs))
    print(len(acceptedvowelpairs))

A: Unicode normalization does not help for described particular character combinations because an excerpt from Unicode database UnicodeData.Txt using simple regex "Latin.*Letter.*with tilde$" gives ÃÑÕãñõĨĩŨũṼṽẼẽỸỹ (no Latin letters Open O, Open E or Alpha). So you need to iterate through both compared strings separately as follows (omitted most of your code above a Minimal, Reproducible Example):
import unicodedata

def lens(word):
    return len(word)

input_lines = ['alyʁ/alɔʁ', 'ɑ̃bisjø/ɑ̃bisjɔ̃ ', 'osi/ɛ̃si', 'bɛ̃ /bɔ̃ ', 'bo/ba', 'bjɛ/bjɛ̃ ']
print(len(input_lines))
for line in input_lines:
    print('')
    #find word ipa transctipts
    line = unicodedata.normalize('NFKC', line.rstrip('\n'))
    line = line.split("/")
    line.sort(key = lens)
    word1, word2 = line[0:2] # the shortest two strings after splitting are the ipa words
    index = i1 = i2 = 0
    while i1 < len(word1) and i2 < len(word2):
        letter1 = word1[i1]
        i1 += 1
        if i1 < len(word1) and unicodedata.category(word1[i1]) == 'Mn':
            letter1 += word1[i1]
            i1 += 1
        letter2 = word2[i2]
        i2 += 1
        if i2 < len(word2) and unicodedata.category(word2[i2]) == 'Mn':
            letter2 += word2[i2]
            i2 += 1
        same = chr(0xA0) if letter1 == letter2 else '#'
        print(index, same, word1, word2, letter1, letter2)
        index += 1
        #if same != chr(0xA0):
        #    break

Output: .\SO\67335977.py
6

0   alyʁ alɔʁ a a
1   alyʁ alɔʁ l l
2 # alyʁ alɔʁ y ɔ
3   alyʁ alɔʁ ʁ ʁ

0   ɑ̃bisjø ɑ̃bisjɔ̃  ɑ̃ ɑ̃
1   ɑ̃bisjø ɑ̃bisjɔ̃  b b
2   ɑ̃bisjø ɑ̃bisjɔ̃  i i
3   ɑ̃bisjø ɑ̃bisjɔ̃  s s
4   ɑ̃bisjø ɑ̃bisjɔ̃  j j
5 # ɑ̃bisjø ɑ̃bisjɔ̃  ø ɔ̃

0 # osi ɛ̃si o ɛ̃
1   osi ɛ̃si s s
2   osi ɛ̃si i i

0   bɛ̃  bɔ̃  b b
1 # bɛ̃  bɔ̃  ɛ̃ ɔ̃
2   bɛ̃  bɔ̃

0   bo ba b b
1 # bo ba o a

0   bjɛ bjɛ̃  b b
1   bjɛ bjɛ̃  j j
2 # bjɛ bjɛ̃  ɛ ɛ̃

Note: diacritic tested as Unicode category Mn; you can test against another condition (e.g. from the following list):

*

*Mn Nonspacing_Mark: a nonspacing combining mark (zero advance width)

*Mc Spacing_Mark   : a spacing combining mark (positive advance width)

*Me Enclosing_Mark : an enclosing combining mark

*M  Mark           : Mn | Mc | Me

A: I am in the process of solving this by just doing a find and replace on these characters before processing it and a reverse find and replace when I'm done.


text:
Q: Error implementing flask_images with python 3.7.3 I am having issues referencing flask_images on jinja2 template... Implementation works on python 2.7 and on img tag () and div (as background image) but doesnt work on python 3.7.3 when implemented on jinja2 template with div tag (as background-image)

IT WORKS PERFECTLY WITH THE CODE BELOW

A: I found the solution to the question..
python flask_image is rendered on html by jinja2 template with single quote.. This was making it not unrecognized ...
Simply put,
I replaced single quote (') with (%27) using jinja in python flask
Code Example


text:
Q: The "Run Inference" doesn't work in Maestro edition I downloaded the maestro edition and was following the starter guide with the Person ontology tutorial. It has been good until i tried the inference example. I clicked "Inference->Run Inferences", in the 'inferences' views, it's empty. nothing inferred. Also with SparQL query, it didn't infer. Should I first configure some reasoners?
SELECT ?subject ?object
WHERE {
    ?subject person:hasChild ?object
}

With the inference configurations, it doesn't show any Williams's children.
The message log is below.


text:
Q: I want to change java class at run time which is already loaded. how to do this? First time  class is created successfully but next time when there is change in class (like add some variables) It throws an error.
Below is my code.
ClassPool pool = ClassPool.getDefault();
        CtClass cc=null;
        final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        if (contextClassLoader != null)
        {
            pool.insertClassPath(new LoaderClassPath(contextClassLoader));
        }
        try{

            cc = pool.makeClass(className);
            cc.defrost();
            for (Entry<String, Class<?>> entry : properties.entrySet()) {
                cc.addField(new CtField(resolveCtClass(entry.getValue()), entry.getKey(), cc));
                // add getter
                cc.addMethod(generateGetter(cc, entry.getKey(), entry.getValue()));
                // add setter
                cc.addMethod(generateSetter(cc, entry.getKey(), entry.getValue()));

            }
            cc.addConstructor(generateConstructor(cc,properties,className));
            CtConstructor defaultCons=new CtConstructor(NO_ARGS, cc);
            defaultCons.setBody(";");
            cc.addConstructor(defaultCons);
            return cc.toClass();
        }catch(Exception e){
            cc = pool.get(className);
            cc.detach();
            cc = pool.makeClass(className);
            cc.defrost();
            for (Entry<String, Class<?>> entry : properties.entrySet()) {
                cc.addField(new CtField(resolveCtClass(entry.getValue()), entry.getKey(), cc));
                // add getter
                cc.addMethod(generateGetter(cc, entry.getKey(), entry.getValue()));
                // add setter
                cc.addMethod(generateSetter(cc, entry.getKey(), entry.getValue()));

            }
            cc.addConstructor(generateConstructor(cc,properties,className));
            CtConstructor defaultCons=new CtConstructor(NO_ARGS, cc);
            defaultCons.setBody(";");
            cc.addConstructor(defaultCons);
            return **cc.toClass();** // getting error at this line
        }

A: You need to write a Java agent and attach it dynamically to transform a class after it was already loaded. A Java agent defines a method named agentmain which takes an instance of Instrumentation as its second argument. With such a Java agent, the changes you are allowed to apply are however limited to changing the body of a method, you cannot add members (fields or methods) or change the signature of existing ones.
You call Instrumentation::redefineClass to apply a redefinition.
You can find articles on how to change loaded code on several places online.

A: Simple answer: you can't (easily).
The point is: when the class is already loaded then the JVM has already information about that class. The "default" classloader simply does not allow you to replace that definition with a new one.
If you want to dynamically exchange class definitions, you have to turn to the advanced topic of writing your own classloader that allows for such things. See here as starting point.


text:
Q: new lambda literal syntax for activerecord callbacks I wonder if this is possible?
after_create -> { some_method_from_model }, if: :should_be_executed?

Syntax is ok, but the Proc will be called/executed or just created?

A: If you want to call a method on the model the best approach would be passing the model as an argument for your lambda, and then using it to invoke the desired method, like so:
after_create -> (model) { model.some_method }, if: :execution_condition_satisfied?

This is because the value of self inside the lambda isn't the model but a Proc object and, without an explicit receiver, Ruby tries to invoke the method in self.
In your example, Ruby will try to find some_model_method in the Proc object. So no, your example would not work, but that's not related to the new lambda literal syntax.
I hope it helps ;)

A: This seems overly complicated to me.  I would just put the if test inside the method which is being called.
after_create :some_method

def some_method
  if condition_satisfied
    #do the stuff
  end
end


text:
Q: Why do images appearing differently when posted on linkedin.com than when posted via the API? When I post a share via the linkedin.com website and then grab its attributes and share them again from the API, the picture doesn't appear the same way.
Here's an example, the bottom post was shared from the web interface and then the top post was shared from the API:

The attributes for these posts are identical. Here are the JSON attributes for the post shared via LinkedIn.com:
"comment"=>"Test1",
"content"=>
{"description"=>"",
"eyebrow_url"=>
"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"shortened_url"=>
"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"submitted_image_url"=>
"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"submitted_url"=>
"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"thumbnail_url"=>
"https://media.licdn.com/media-proxy/ext?w=80&h=100&hash=83SZltJ4k6E4eW%2B%2B%2F4R86FIVsLU%3D&url=http%3A%2F%2Fimage-store.slidesharecdn.com%2F47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"title"=>"Screen Shot 2014-11-13 at 3.37.02 PM.png"},

And the attributes for the post shared via the REST API:
"comment"=>"Test1",
"content"=>
{"description"=>" ",
"eyebrow_url"=>
"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"shortened_url"=>
"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"submitted_image_url"=>
"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"submitted_url"=>
"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"thumbnail_url"=>
"https://media.licdn.com/media-proxy/ext?w=80&h=100&hash=83SZltJ4k6E4eW%2B%2B%2F4R86FIVsLU%3D&url=http%3A%2F%2Fimage-store.slidesharecdn.com%2F47dc092f-2411-4490-b8f0-8f5e587d1857-large.png",
"title"=>"Screen Shot 2014-11-13 at 3.37.02 PM.png"},

Here's the HTTP request used to create the post via the API:
HTTP POST (935.00ms) https://api.linkedin.com:443/v1/people/~/shares
Request body {"visibility":{"code":"anyone"},"comment":"Test1","content":{"description":"","submitted_image_url":"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png","submitted_url":"http://image-store.slidesharecdn.com/47dc092f-2411-4490-b8f0-8f5e587d1857-large.png","title":"Screen Shot 2014-11-13 at 3.37.02 PM.png
"}}

Is this a bug in the API or a difference between how LinkedIN handles shares from the API vs the web interface? Is there a workaround?

A: The Share API calls are not currently processed through the same crawler interface that shares made via linkedin.com are subject too.
When sharing via API, it will only use the information that is directly provided as part of the API request.  Via the website, a crawler script attempts to analyze the target page automatically for the necessary information.


text:
Q: Can we call function inside an function SQL Server 2005 ALTER function [dbo].[getEmployeeID](@ID int) returns table
as
  begin
  return (
    select * from [dbo].[gtEmployeeName](2)
    select * from Employees where EmployeeID = @ID)
end

here [dbo].[gtEmployeeName] is an other function that I am trying to call.
I am getting an error,  can we call or is there any syntax problem?

Msg 156, Level 15, State 1, Procedure getEmployeeID, Line 6
  Incorrect syntax near the keyword 'select'.
  Msg 102, Level 15, State 1, Procedure getEmployeeID, Line 6
  Incorrect syntax near ')'.

Thanks
Prince

A: If [dbo].[gtEmployeeName] returns scalar you probably are looking for
ALTER function [dbo].[getEmployeeID](@ID int) returns table
as
begin
return (
    select *, [dbo].[gtEmployeeName](2) as EmpName from Employees where EmployeeID=@ID)
end

If [dbo].[gtEmployeeName] returns table you probably are looking for
ALTER function [dbo].[getEmployeeID](@ID int) returns table
as
begin
return (
    select * from [dbo].[gtEmployeeName](2) EN
    inner join Employees E on EN.EmployeeID = E.EmployeeID
    where EmployeeID=@ID)
end

Update the join to outer if that is what you need. Also update the join condition (the example assumes that the returned table from gtEmployeeName has a column EmployeeID and that can be used for joining to Employees.

A: Yes you can call a function inside a function.
In fact, you can call the current function inside the function, to cause a loop.
What error are you getting? Your error is most likely related to something else


text:
Q: Apply different color depending of width size of a div? I am trying to apply a different color to a div depending its width size.
My html is this

And my CSS is this:
div._progress{
    background-color: black;
    width: 100%;
    height: 20px;
    padding: 1px;
  }
  div.progress{
    background-color: green;
    border-radius: 25%;
    width: 50%;
    height: 100%;
    -webkit-transition:width 350ms ease-in-out, height 350ms ease-in-out;
    -moz-transition:width 350ms ease-in-out, height 350ms ease-in-out;
    -o-transition:width 350ms ease-in-out, height 350ms ease-in-out;
    transition:width 350ms ease-in-out, height 350ms ease-in-out;
  }

From my javascript I change the width size with document.getElementById......
How can I change the color of the progress for example when the inside bar is the 90% of the container width to red?
Something like this

Thanks

A: you can use linear gradient property. not necessary to do in js.

#grad1 {
  height: 20px;
  background: linear-gradient(to left, #FF5733 30%, #36FF33 30%, #36FF33 100%);
}


text:
Q: Multiple DIV inside DIV - new line in IE7 My using below code

<MARQUEE>

1

2

3

</MARQUEE>

The problem is that 1,2,3 are displayed vertically. This happening only in IE7. What i have to change for this to display this in horizontally?
Thanks in Advance

A: Please don't use the marquee HTML tag
To make div elements display horizontally try something like this :
ul li div {
    float:left;
}

example here


text:
Q: Insert other values when using Insert Ignore I got my answer from Bill. But how do I insert other default values not found on the loop select?
I'm doing this which works:
SET @createdAt = STR_TO_DATE(NOW(), '%Y-%m-%d %H:%i:%s');

INSERT IGNORE INTO fancy_table (userId, content, createdAt)

-- Values
SELECT
  userId,
  content,
  -- I faked this
  REPLACE(some_random_col, 'sometimes-value-does-not-match', @createdAt) as createdAt
FROM users
WHERE foo = 'bar';

What if I want to update more columns of fancy_table, how to do that? The "fake" REPLACE column is wrong to me.
EDIT:
How can I achieve something like this:
SET @createdAt = STR_TO_DATE(NOW(), '%Y-%m-%d %H:%i:%s');

INSERT IGNORE INTO fancy_table (userId, content, createdAt, etc...)

VALUES (
  (SELECT
    userId,
    content
  FROM users
  WHERE foo = 'bar';),

  @createdAt,

  etc...
)

A: You can use @createdAt directly in the SELECT statement:
SET @createdAt = STR_TO_DATE(NOW(), '%Y-%m-%d %H:%i:%s');

INSERT IGNORE INTO fancy_table (userId, content, createdAt)
SELECT
  userId,
  content,
  @createdAt
FROM users
WHERE foo = 'bar';

but, @createdAt , is actually the current timestamp which you can get with CURRENT_TIMESTAMP or NOW():
INSERT IGNORE INTO fancy_table (userId, content, createdAt)
SELECT
  userId,
  content,
  CURRENT_TIMESTAMP
FROM users
WHERE foo = 'bar';


text:
Q: How do I get a ListBox to display all info for an "ID" from a Textbox (ASP.NET C#) I'm working on a project where I want to display all of the incident information (from Database) for a Customer (which I get from a textbox/ user input).
I'm struggling to fill the ListBox and am not sure that I have the right idea so far for using the "RowFilter" function.
public partial class CustomerSurvey : System.Web.UI.Page
{
    private Incident incidentInformation;
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnGet_Incidents(object sender, EventArgs e)
    {
        incidentInformation = this.GetInfoForSelectedCustomerID();
    }

    private Incident GetInfoForSelectedCustomerID()
    {
        //get row from AccessDataSource based on value in dropdownlist
        DataView customersTable = (DataView)
            SqlDataSource2.Select(DataSourceSelectArguments.Empty);
        customersTable.RowFilter =
            "CustomerID = '" + txtCustomerID_ForIncidents + "'";
        DataRowView row = (DataRowView)customersTable[0];

        //create a new product object and load with data from row
        Incident i = new Incident();

        i.IncidentID = (int)row["IncidentID"];
        i.CustomerID = (int)row["CustomerID"];
        i.ProductCode = row["ProductCode"].ToString();
        i.TechID = (int)row["TechID"];
        i.DateOpened = (DateTime)row["DateOpened"];
        i.DateClosed = (DateTime)row["DateClosed"];
        i.Title = row["Title"].ToString();
        i.Description = row["Description"].ToString();

        return i;
    }

    private void DisplayInfo()
    {
        Incident incident = (Incident)Session["Reservation"];

        lstCustomers.Display
    }

As you can see above the function DisplayInfo is unfinished. This is because I don't know how to fill the ListBox.
Another thing that I am considering is that there might be multiple incidents to a customer and I am not sure that I have the right approach with the class.
Thanks!

A: Do you want to display the data in the database based on the Textbox value in the ListBox? If so, you can refer to below code.
If I misunderstand your requirement, please post more details information about your requirement.
Aspx,

<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
            CustomerId:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="btnGet_Incidents" />
            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ThreadDemoConnectionString %>" SelectCommand="SELECT [CustomerId], [Name], [Country] FROM [Customers]"></asp:SqlDataSource>

Aspx.cs:
protected void btnGet_Incidents(object sender, EventArgs e)
{
    ListBox1.Items.Clear();
    GetInfoForSelectedCustomerID();
}

private void GetInfoForSelectedCustomerID()
{

    //get row from AccessDataSource based on value in dropdownlist
    DataView customersTable = (DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
    customersTable.RowFilter = "CustomerId = '" + TextBox1.Text + "'";
    DataRowView row = (DataRowView)customersTable[0];

    ListBox1.Items.Add(row["CustomerId"].ToString());
    ListBox1.Items.Add(row["Name"].ToString());
    ListBox1.Items.Add(row["Country"].ToString());

}

The result,


text:
Q: Threads and sync I build a GTA program that when player is using resource no one else can use it
I tried to change priorities but this didn't seems to help.
you can see that after player4 started using guns also player3 and he shouldn't.
what I am trying to do is that when a player using an object no one else should be able to access it until the player finished.
thanks in advance!
Resources:
package GTA;
public class Resources
{
    static final Object guns = "guns";
    static final Object drugs = "drugs";
    static final Object money = "money";

    public static void main(String[] args)
    {
        Player[] p = new Player[4];
        p[0] = new Player("player1");
        p[1] = new Player("player2");
        p[2] = new Player("player3");
        p[3] = new Player("player4");
        p[0].start();
        p[1].start();
        p[2].start();
        p[3].start();
    }
}

Player:
package GTA;
public class Player extends Thread
{
    public Player(String name) {super(name);}
    public void run()
    {
        synchronized (Resources.guns)
        {
            System.out.println(getName() + " is using the guns");
            setPriority(7);

            try {   sleep(2000);}
            catch(InterruptedException e) {e.printStackTrace();}
        }

        synchronized (Resources.drugs)
        {
            System.out.println(getName() + " does some drugs");
            setPriority(4);

            try {   sleep(2000);}
            catch(InterruptedException e) {e.printStackTrace();}
        }

        synchronized (Resources.money)
        {
            System.out.println(getName() + " is swimming in money right now");
            setPriority(1);

            try {   sleep(2000);}
            catch(InterruptedException e) {e.printStackTrace();}
        }
        System.out.println(getName() + " Wasted!");
    }
}

Output:
player1 is using the guns
player1 does some drugs
player4 is using the guns
player3 is using the guns
player4 does some drugs
player1 is swimming in money right now
player3 does some drugs
player4 is swimming in money right now
player1 Wasted!
player2 is using the guns
player4 Wasted!
player2 does some drugs
player3 is swimming in money right now
player2 is swimming in money right now
player3 Wasted!
player2 Wasted!

A:
you can see that after player4 started using guns also player3 and he
shouldn't.

The synchronization block will not tell threads to skip that block if a threads is already inside. It just tells the thread to wait until the other thread is finished. Therefore, in your code all threads will execute all the those three blocks protected by the synchronized, regardless of how long the thread stay inside that block sleep(2000); albeit the execution of those blocks will be performed sequentially.
If you want to limit the number of threads that can access a certain resource (e.g., execute a block of code) you need to use Semaphore (or alike) for that purpose.

what I am trying to do is that when a player using an object no one
else should be able to access it until the player finished.

If by object you mean separately the guns, drugs, money. Then you achieve that there will not be multiple player (i.e., threads) using those objects simultaneously.
If by "after the player have finish" you mean the entire run then you need to synchronize the entire block of the run() method using a single lock.

A: You have three monitors by three objects and each of them has a lock independently.
You should take a lock by using one monitor for object Resource.
You can try that:
public class Solution01 {

static final Object guns = "guns";

public static void main(String[] args) {
    Player[] p = new Player[4];
    p[0] = new Player("player1");
    p[1] = new Player("player2");
    p[2] = new Player("player3");
    p[3] = new Player("player4");
    p[1].setPriority(3);
    p[2].setPriority(2);
    p[3].setPriority(1);
    p[0].start();
    p[1].start();
    p[2].start();
    p[3].start();
}

public static class Player extends Thread {

    public Player(String name) {
        super(name);
    }

    public void run() {
        synchronized (Solution01.guns) {
            System.out.println(getName() + " is using the guns");
            try {
                sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(getName() + " does some drugs");
            try {
                sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(getName() + " is swimming in money right now");
            try {
                sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(getName() + " Wasted!");
        }
    }
}

}

A: I think the following is what you are looking for. If you want to limit the threads to behave in a synchronous manner when using resources, you should synchronize the access on the resource:
Resources class:
Example is only for the guns:
class Resources {
static synchronized void useGun(String playerName) {
    System.out.println(playerName + "is using the gun");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    Player[] p = new Player[4];
    p[0] = new Player("player1");
    p[1] = new Player("player2");
    p[2] = new Player("player3");
    p[3] = new Player("player4");
    p[0].start();
    p[1].start();
    p[2].start();
    p[3].start();
}
}

Player class:
class Player extends Thread {

private String name;

public Player(String name) {
    super(name);
    this.name = name;
}

public void run() {
    Resources.useGun(name);
    System.out.println(getName() + " Wasted!");
}
}


text:
Q: Make Zend\Debug\Debug::dump() only dump in development mode? For quick debugging I prefer Zend\Debug\Debug::dump(). The problem: Sometimes I forget to remove old dump statements and they make it into production.
It would be great if Debug::dump() only printed something, when I'm in development mode.
Is there any elegant way to achieve this without having to transform Zend\Debug\Debug into a service? I like the plain and simple static method call. Probably through setting an env var when enabling dev mode?

A: In your /public/.htaccess add this code. SetEnv APPLICATION_ENV "development"
In your /public/index.php file
/**
 * Set global ENV. Used for debugging
 */
if (isset($_SERVER['APPLICATION_ENV']) && $_SERVER["APPLICATION_ENV"] === 'development') {
    define("APP_ENV", 'development');
} else {
    define("APP_ENV", "production");
}

/**
 * Set default php.ini settings.
 *
 * Below lines includes security|error fixes
 */

/**
 * Handle reporting level
 */
error_reporting((APP_ENV === 'development' ? E_ALL : 0));

/**
 * Log errors into a file
 */
ini_set("log_errors", (APP_ENV === 'development'));

/**
 * Display of all other errors
 */
ini_set("display_errors", APP_ENV === 'development');

/**
 * Display of all startup errors
 */
ini_set("display_startup_errors", APP_ENV === 'development');

/**
 * Catch an error message emitted from PHP
 */
ini_set("track_errors", APP_ENV === 'development');

/**
 * Avoid serving non .php files as .php files
 */
ini_set('cgi.fix_pathinfo', 0);

/**
 * Helps mitigate xss
 */
ini_set('session.cookie_httponly', 1);

/**
 * Prevents session fixation
 */
ini_set('session.use_only_cookies', 1);

/**
 * Fixes files and server encoding
 */
mb_internal_encoding('UTF-8');

/**
 * Some server configurations are missing a date timezone
 */
if (ini_get('date.timezone') == '') {
    date_default_timezone_set('UTC');
}

When your site goes public, just change the .htaccess env variable to production and all debugging options will disappear. That's the way how i disable such debug options and modules and it works fine.


text:
Q: Remove override annotation even though JDK Compliance has been set to 1.6 I have annoying problem with this override annotation, I have come to google to find a solution but I can't find any clue. I have set the JDK Compliance to 1.6 it has a default, but eclipse still ask me to remove the override, what should I do to overcome this thing?
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
public class HelloList extends Activity {
ListView list;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hello_list);
    list = (ListView)findViewById(R.id.list);
    String[] values = new String[]{"StudentSite", "Staffsite", "BAAK", "Seminar"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
    list.setAdapter(adapter);

    list.setOnItemClickListener(new OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
        {
            Toast.makeText(getApplicationContext(), pos, Toast.LENGTH_LONG).show();
        }
    });
}

A: Try it to set the SDK to 1.7 version,then it will not ask u to remove the override
Steps are:

*

*Select the Project.

*Right click,select the properties.

*Select java compiler.
set the value to 1.7 and clean the project from menu bar in project tab.


text:
Q: How to obtain a nonzero order parameter for a symmetry-breaking quantum phase transition? If $\hat{m_z}=\frac{1}{N}\sum_i \hat{\sigma^z_i}$ is an order parameter for finite quantum system (transverse Ising model, say), then it will never break the $\mathbb{Z}_2$ symmetry since $\langle\psi_0|\hat{m_z}|\psi_0\rangle=0$ for the ground state $|\psi_0\rangle$ that satisfies the symmetry of system.
This is in fact not a unique problem to quantum systems.
But for the classical systems, a quick fix that I'm aware of is replacing the scaling $m_z\sim \tau^\beta$ by $m_z^2\sim \tau^{2\beta}$, where $\tau$ is the control parameter and $\beta$ a critical exponent.
(a further possible step is the Binder cumulant/bimodality coefficient defined as the fourth moment scaling as $\tau^{4\beta}$ normalized by this second moment squared, so that no net scaling with the order parameter remains),
A naive, straightforward generalization to quantum systems is thus working with $\langle \hat{m}_z^2\rangle\sim \tau^{2\beta}$. This seems to be indeed what is done, for example in https://doi.org/10.1103/PhysRevB.87.174302 (eq. 54). But now I saw in a response to a different question here https://physics.stackexchange.com/a/460031/25292 that the scaling of the power of a variable should not be so trivial?
So, my questions are

*

*Is this procedure of squaring the operator of the order parameter and replacing $\beta\rightarrow 2\beta$  valid?

*In case not, what would be the alternative, for finite-size scaling purposes?

I just saw in an original paper on 1D quantum Ising, https://doi.org/10.1016/0003-4916(70)90270-8 that they used the square root of only the infinite-range correlation instead of from the full squared magnetisation. But it seems unclear what would be the result of this in a finite system.

A: Up to some sloppy notations, what is written in the question is correct.
Being more rigorous with notations will help clarify the problem.
I will assume that the system is classical, since adding quantum fluctuations will only change the scaling by known scaling relations if the transition is at $T=0$ (which depends on the dynamical exponent $z$), or will not change anything if the transition is at finite temperature.
Let us call $s(x)$ the microscopic field, and $M=\langle s(x)\rangle$ the (natural) order parameter. Let us call $s_0= L^{-d} \int d^dx\, s(x)$, where $L$ is the linear size of the system, and $d$ its dimension. We have by invariance by translation that $M=\langle s_0\rangle$.
Scaling theory tells us that close to the transition (parametrized by the reduced temperature $\tau$), we have
$$
M\propto |\tau|^\beta.
$$
This can be obtained by coupling $s_0$ to a source field $j$ (which is a volume times a magnetic field), and looking at the scaling behavior of the free energy (not the free energy density):
$$
F(\tau,j) = F(|\tau| s^{1/\nu},j s^{-\beta/\nu})= F_1( j |\tau|^{\beta}),
$$
where the last line is obtained from $s=|\tau|^{-\nu}$. Because the theory is not critical in presence of a symmetry breaking source, we know that $F_1$ is analytic in its variable. Therefore, we immediately obtain that
$$
\langle s_0^k\rangle = |\tau|^{k\beta},
$$
as can also be obtained using Binder's probability distribution of $s_0$.
For $k=2$, this is in agreement with the scaling of the susceptibility, since
$$
\chi = L^{-d} \int d^dx d^dy \,\langle s(x) s(y)\rangle=L^d \langle s_0^2\rangle,
$$
using that $\gamma=\nu d -2\beta$.
In particular, this means that we can relate all the critical scaling of zero-momenta correlation functions to $\beta$ (up to some $\nu d$ terms). However, this does not mean that all correlation functions have scaling exponents that are simply related to $\beta$ and $\nu$. For instance, the specific heat exponent $\alpha =2-\nu d$ does not depend on $\beta$ (or equivalently to $\eta$). There is no contradiction because
$$
C_V = \int d^d x d^d y\, \langle s(x)^2s(y)^2\rangle
$$
cannot be written in terms of $s_0$ alone.


text:
Q: Force page to reload from server instead of load the cached version I have webpage A. The user clicks on a form to submit data, and it takes him to webpage B. When he clicks the back button, I need webpage A to be refreshed from the server, rather that loaded from cache. I have this: <meta http-equiv="expires" content="0"> but it doesnt seem to work. I have also tried setting a variable on page B (session variable via php) and then check for it on page A and refresh (or not) according to its existence. This doest seem to work either. The basic code for that is:
Page A:
<?php
if(isset($_SESSION['reloadPage'])) {
unset($_SESSION['reloadPage']);
echo'
<script>
window.location.replace("/****/****/*****.php");
</script>
';
}
?>

And on page B:
$_SESSION['reloadPage'] = 1;

With the PHP solution, it simply keeps trying to refresh the page in a never ending loop. Something in my logic missing? Is this the right way to go about it?
EDIT
Upon further investigation, when you tell the browser to not cache the page, does that force a full server side refresh as well? That's what I need. A full server side refresh of the page.

A: OK try this instead:
<?php
    if(!session_id()) {
        @session_start();
    }
    header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
    header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Cache-Control: post-check=0, pre-check=0', false);
    header('Pragma: no-cache');

    if(isset($_SESSION['form_submitted'])) {
        unset($_SESSION['form_submitted']);
        header('Location: ?' . uniqid());
        #header('Refresh: 0');
    }
?>

You will need to set $_SESSION['form_submitted'] = true on page 2.

A: Try with all three:
<meta http-equiv="cache-control" content="no-cache"> <!-- tells browser not to cache -->
<meta http-equiv="expires" content="0"> <!-- says that the cache expires 'now' -->
<meta http-equiv="pragma" content="no-cache"> <!-- says not to use cached stuff, if there is any -->

A: <?php
    session_start();
    if(isset($_SESSION['reloadPage'])) {
        unset($_SESSION['reloadPage']);
           //no outputting code above header
        header("Cache-Control: no-cache, must-revalidate");
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
        header("Location: http://www.mypage.com/");
    }
?>

A: I know this is old question and already have the answer (that not refreshing from the server). So I would like to share a solution using jQuery.
$('#back-button').click(function(){
   setTimeout(location.reload(true), 1000);
});

Explanation:
As you click the back button, the setTimeout will triggered after 1 second (1000 milliseconds). Then, the page will reload from the server as the parameter inside the reload is true.
If you put true inside the reload it will reload from the server while if you put false it will reload from the cache. Source w3schools.

A: Your JavaScript should be...
window.location = "/****/****/*****.php"

I think that should fix your loop.

A: <?php
  session_start();
  if(isset($_SESSION['reloadPage'])) {
  unset($_SESSION['reloadPage']);
  echo'
  <script>
  window.location.replace("/****/****/*****.php");
  </script>
  ';
}
?>


text:
Q: JQuery simple tooltip I'm looking for some JQuery tooltip plugin or even a simple solution to show a dynamic value from an input field when I mouse over a determined link (text or image)
I've tried a lot of plugins but none can give me the dynamic value of the field.
Example:
Input field:
input type="text" name="example" id="example" value=""
Link for mouseover/tooltip:
a href="#" id="tooltip">value</a
The value of the input field will be changed by another JQuery function and it's working
fine, but when I try to show it's value using any tooltip plugin, doesn't work.
If I simple use the alert() function, it's working fine.
I don't need any fancy tooltip, only show the value of the input field.
Please, any solution?

A: We use tipsy for our tooltips on twitter.com, and it works great.  It can generate the tooltip text dynamically using a callback function, like this:
HTML:
<input type="text" id="example" value="foo" />

JavaScript:
$("#example").tipsy({
  title: function() {
    return $(this).val();
  }
});

Here's a complete example/demo.  There are plenty of configuration options to suit your needs.

A: look on this library
http://flowplayer.org/tools/demos/tooltip/index.html


text:
Q: How do i get the screen to pause?
Possible Duplicate:
How to stop C++ console application from exiting immediately?

So im learning c++ and i was given this example and i wanted to run it. But i cannot get it to stay up, unless i change it. How do i get Microsoft visual 2010 to keep up the screen when it gets to the end of the program after I release it?
#include<iostream>
using namespace std;

int area(int length, int width);        /* function declaration */

/* MAIN PROGRAM: */
int main()
{
    int this_length, this_width;

    cout << "Enter the length: ";             /* <--- line 9 */
    cin >> this_length;
    cout << "Enter the width: ";
    cin >> this_width;
    cout << "\n";                             /* <--- line 13 */

    cout << "The area of a " << this_length << "x" << this_width;
    cout << " rectangle is " << area(this_length, this_width);

    return 0;
}
/* END OF MAIN PROGRAM */

/* FUNCTION TO CALCULATE AREA: */
int area(int length, int width)   /* start of function definition */
{
    int number;

    number = length * width;

    return number;
}                                 /* end of function definition */
/* END OF FUNCTION */

A: In Visual C++ you can either:

*

*Put a breakpoint at the closing brace of main and run attached to the debugger (Debug -> Start Debugging).  When the breakpoint is hit you will be able to view the console window.

*Run detached from the debugger (Debug -> Start Without Debugging).  When the application terminates, the console window will stay open with a "Press any key to continue..." prompt.

A: I usually use cin.getchar() to wait for a character.

A: Try adding system("PAUSE"); to the end of main before the return statement.
This executes the PAUSE system command which waits for a key to be pressed.

A: The easiest way is to wait for the user to press a key before returning from main.

A: You already have the answer in your code.. add another cin at the end of your program ;P user would have to press enter for program to continue and exit


text:
Q: I encountered "unary operator expected" in a Bash script In my Bash script, I have a function to return 0 or 1 (true or false) for the later main function's condition.
function1 () {
    if [[ "${1}" =~ "^ ...some regexp... $" ]] ; then
        return 1
    else
        return 0
    fi
}

Then in my main function:
main () {
    for arg in ${@} ; do
        if [ function1 ${arg} ] ; then
            ...
        elif [ ... ] ; then
            ...
        fi
    done
}

However, when I ran this script it always gave me an error message:

[: function1: unary operator expected

How can I fix this?

A: You are making the common mistake of assuming that [ is part of the if command's syntax.  It is not; the syntax of if is simply
if command; then
    ... things which should happen if command's result code was 0
else
    ... things which should happen otherwise
fi

One of the common commands we use is [ which is an alias for the command test.  It is a simple command for comparing strings, numbers, and files.  It accepts a fairly narrow combination of arguments, and tends to generate confusing and misleading error messages if you don't pass it the expected arguments.  (Or rather, the error messages are adequate and helpful once you get used to it, but they are easily misunderstood if you're not used.)
In your main function, the call to [ appears misplaced.  You probably mean
if function "$arg"; then
    ...
elif ... ; then ...

By the way, for good measure, you should also always quote your strings.  Use "$1" not $1, and "$arg" instead of $arg.
The historical reasons for test as a general kitchen sink of stuff the authors didn't want to make part of the syntax of if is one of the less attractive designs of the original Bourne shell.  Bash and zsh offer alternatives which are less unwieldy (like the [[ double brackets in bash, which you use in your function1 definition), and of course, POSIX test is a lot more well-tempered than the original creation from Bell Labs.
As an additional clarification, your function can be simplified to just
function1 () {
    ! [[ "$1" =~ "^ ...some regexp... $" ]]
}

That is, perform the test with [[ and reverse its result code.  (The "normal" case would be to return 0 for success, but maybe you are attempting to verify that the string doesn't match?)


text:
Q: 'Invalid Verb' error only when Calling Inkscape as a subprocess When I call the following in the command line it works like a charm:
inkscape --with-gui --batch-process --export-filename=- \
    --actions="select-all;ObjectToPath" \
    /full/path/to/example.svg

But when I open Node.js and make the same call in a subprocess like so:
const cp = require("child_process");
var child = cp.spawn(
    "/usr/bin/inkscape",
    [
        "--with-gui",
        "--batch-process",
        "--export-filename=-",
        '--actions="select-all;ObjectToPath"',
        "/full/path/to/example.svg",
    ],
    {
        cwd: process.cwd(),
        detached: true,
        stdio: "inherit",
    }
);

I get the following error:
Unable to find: "select-all
verbs_action: Invalid verb: "select-all
Unable to find: ObjectToPath"
verbs_action: Invalid verb: ObjectToPath"

and the file is returned (printed to stdout) unchanged.  Any Idea why the verbs are not found when running Inkscape as a subprocess but not calling it directly from the terminal?   I get this same error on ubuntu (20.04) and OSX using the latest Inkscape (1.0.1+r73).

A: When you use cp.spawn with an array of arguments, you don't need to internally quote "select-all;ObjectToPath" like you would with a shell. (In a shell, the quotes prevent the shell from tokenizing the command line into two lines. Due to the same mechanism - or lack thereof - attempting to use shell variables such as $$ or environment variables such as $PATH would fail when you use  cp.spawn, since there's nothing to parse that.)
I would imagine
const cp = require("child_process");
var child = cp.spawn(
  "/usr/bin/inkscape",
  [
    "--with-gui",
    "--batch-process",
    "--export-filename=-",
    "--actions=select-all;ObjectToPath",
    "/full/path/to/example.svg",
  ],
  {
    cwd: process.cwd(),
    detached: true,
    stdio: "inherit",
  },
);

would do the trick for you.


text:
Q: Random points in sphere following density curve I want to generate a series of points in a sphere following a density curve (x is distance to sphere center, y is quantity of point at this distance) and I have no idea where to begin with.
Thanks in advance !


text:
Q: How to delete lines having specific text using sed command? I saw a similar Question on this forum but this question is little different from those questions. Hence please do not consider this as a duplicate.
I have a file containing data as
blah blah
blah blah Select from table blah blah QWERTY blah
Select from table
QWERTY Here
blah blah

Now I want to delete all the lines having both Select from table and QWERTY
Expected Output:
blah blah
Select from table
QWERTY Here
blah blah

I tried as below:
sed /*Select from table*QWERTY*/d file.txt

But it is not working. Could anyone please help on this?

A: You was close with you sed attempt:
$ sed '/Select from table.*QWERTY/d' file
blah blah
Select from table
QWERTY Here
blah blah

You should always quotes the script with single quotes and don't confuse shell globbing with regular expressions. To match zero or more of any character using regular expressions is .*.

If order is guaranteed then a simply grep will do using the -v option:
$ grep -v 'Select from table.*QWERTY' file
blah blah
Select from table
QWERTY Here
blah blah

If order isn't guaranteed then used a language such as awk where you can combine regular expression matches with logical operators:
$ awk '!/Select from table/||!/QWERTY/' file
blah blah
Select from table
QWERTY Here
blah blah


text:
Q: Spring Boot Parent and Spring Cloud starter gateway version issue I am forced to use/mention Spring cloud gateway version because my organization uses nexus repo.
I am using spring boot parent version 2.5.12, could you please let me know which version of spring
cloud starter gateway should I use. I have tried 3.x.x version for gateway but no use.

A: You can refer to Spring Boot and Spring Cloud Compatibility Matrix in the below
Check for Release train Spring Boot compatibility in the below
https://spring.io/projects/spring-cloud

A: See compatible version between Spring Cloud (Spring Cloud Gateway) with Spring Boot at here. https://spring.io/blog/2022/05/27/spring-cloud-2021-0-3-is-available-compatible-with-spring-boot-2-7-0
https://github.com/spring-cloud/spring-cloud-release/wiki
Choose correct versions pair for you.
For example: Spring Cloud Gateway 3.1.3 (belong to Spring Cloud 2021.0.3 Release Train) works with Spring Boot 2.6.x and Spring Boot 2.7.x


text:
Q: How to downgrade a certain ubuntu 10.04 package (php) back to karmic? I've updated from 9.10 to 10.04, but unfortunately the PHP provided with 10.04 is not yet supported by zend optimizer.
As far as I understand, I need to somehow replace the PHP 5.3 package provided under 10.04 with an older PHP 5.2 package provided under 9.10. However I'm not sure whether this is the right way to downgrade PHP and if yes, I don't know how to replace the 10.04 package with 9.10 package.
Could you please help me with that?

A: This thread will tell you exactly how to downgrade PHP from 5.3 to 5.2 in Ubuntu 10.04:
http://ubuntuforums.org/archive/index.php/t-1447401.html
Update: the OP commented below that the following script found here solved his issue.
#!/bin/bash
# by Ruben Barkow (rubo77) http://www.entikey.z11.de/

# Originally Posted by Bachstelze http://ubuntuforums.org/showthread.php?p=9080474#post9080474
# OK, here's how to do the Apt magic to get PHP packages from the karmic repositories:

echo "Am I root?  "
if [ "$(whoami &2>/dev/null)" != "root" ] && [ "$(id -un &2>/dev/null)" != "root" ] ; then
  echo "  NO!

Error: You must be root to run this script.
Enter
sudo su
"
  exit 1
fi
echo "  OK";

#install aptitude before, if you don`t have it:
apt-get install aptitude
# or if you prefer apt-get use:
# alias aptitude='apt-get'

# finish all apt-problems:
aptitude update
aptitude -f install
#apt-get -f install

# remove all your existing PHP packages. You can list them with dpkg -l| grep php
PHPLIST=$(for i in $(dpkg -l | grep php|awk '{ print $2 }' ); do echo $i; done)
echo these pachets will be removed: $PHPLIST
# you need not to purge, if you have upgraded from karmic:
aptitude remove $PHPLIST
# on a fresh install, you need purge:
# aptitude remove --purge $PHPLIST

#Create a file each in /etc/apt/preferences.d like this (call it for example /etc/apt/preferences.d/php5_2);
#
#Package: php5
#Pin: release a=karmic
#Pin-Priority: 991
#
#The big problem is that wildcards don't work, so you will need one such stanza for each PHP package you want to pull from karmic:

echo ''>/etc/apt/preferences.d/php5_2
for i in $PHPLIST ; do echo "Package: $i
Pin: release a=karmic
Pin-Priority: 991
">>/etc/apt/preferences.d/php5_2; done

# duplicate your existing sources.list replacing lucid with karmic and save it in sources.list.d:
#sed s/lucid/karmic/g /etc/apt/sources.list | sudo tee /etc/apt/sources.list.d/karmic.list

# better exactly only the needed sources, cause otherwise you can get a cachsize problem:
echo "# needed sources vor php5.2:
deb http://old-releases.ubuntu.com/ubuntu/ karmic main restricted
deb-src http://old-releases.ubuntu.com/ubuntu/ karmic main restricted

deb http://old-releases.ubuntu.com/ubuntu/ karmic-updates main restricted
deb-src http://old-releases.ubuntu.com/ubuntu/ karmic-updates main restricted

deb http://old-releases.ubuntu.com/ubuntu/ karmic universe
deb-src http://old-releases.ubuntu.com/ubuntu/ karmic universe
deb http://old-releases.ubuntu.com/ubuntu/ karmic-updates universe
deb-src http://old-releases.ubuntu.com/ubuntu/ karmic-updates universe

deb http://old-releases.ubuntu.com/ubuntu/ karmic multiverse
deb-src http://old-releases.ubuntu.com/ubuntu/ karmic multiverse
deb http://old-releases.ubuntu.com/ubuntu/ karmic-updates multiverse
deb-src http://old-releases.ubuntu.com/ubuntu/ karmic-updates multiverse

deb http://old-releases.ubuntu.com/ubuntu karmic-security main restricted
deb-src http://old-releases.ubuntu.com/ubuntu karmic-security main restricted
deb http://old-releases.ubuntu.com/ubuntu karmic-security universe
deb-src http://old-releases.ubuntu.com/ubuntu karmic-security universe
deb http://old-releases.ubuntu.com/ubuntu karmic-security multiverse
deb-src http://old-releases.ubuntu.com/ubuntu karmic-security multiverse
" > /etc/apt/sources.list.d/karmic.list

aptitude update

apache2ctl restart

echo install new from karmic:
aptitude -t karmic install $PHPLIST

# at the end retry the modul libapache2-mod-php5 in case it didn't work the first time:
aptitude -t karmic install libapache2-mod-php5

apache2ctl restart

A: This post tell you how to install php from "karmic" repository:
http://mrkandy.wordpress.com/2010/04/16/install-php-5-2-x-in-ubuntu-10-04-lucid/
Steps:
php_installed=`dpkg -l | grep php| awk '{print $2}' |tr "\n" " "`

# remove all php packge
sudo aptitude purge $php_installed

# use karmic for php pakage
# pin-params:  a (archive), c (components), v (version), o (origin) and l (label).
echo -e "Package: php5\nPin: release a=karmic\nPin-Priority: 991\n"  | sudo tee /etc/apt/preferences.d/php > /dev/null
apt-cache search php5-|grep php5-|awk '{print "Package:", $1,"\nPin: release a=karmic\nPin-Priority: 991\n"}'|sudo tee -a /etc/apt/preferences.d/php > /dev/null
apt-cache search -n libapache2-mod-php5 |awk '{print "Package:", $1,"\nPin: release a=karmic\nPin-Priority: 991\n"}'| sudo tee -a /etc/apt/preferences.d/php > /dev/null
echo -e "Package: php-pear\nPin: release a=karmic\nPin-Priority: 991\n"  | sudo tee -a /etc/apt/preferences.d/php > /dev/null

# add karmic to source list
egrep '(main restricted|universe|multiverse)' /etc/apt/sources.list|grep -v "#"| sed s/`lsb_release -s -c`/karmic/g | sudo tee /etc/apt/sources.list.d/karmic.list > /dev/null

# update package database (use apt-get if aptitude crash)
sudo apt-get update

# install php
sudo apt-get install $php_installed
# or sudo aptitude install -t karmic php5-cli php5-cgi //for fcgi
# or  sudo apt-get install -t karmic  libapache2-mod-php5 //for apache module

sudo aptitude hold `dpkg -l | grep php5| awk '{print $2}' |tr "\n" " "`
#done


text:
Q: Unordered list doesn't span whole of div I'm have a ul in a div (left-nav-bar). I'm trying to get the ul to span across the whole div when the user hovers over it, but there is whitespace generated before each li and I'm not sure why.

I've tried:
.nav-container ul{
    width: 100%;
}

Which allows the ul to extend beyond the text, but doesn't address the whitespace.
Here is a fiddle: https://jsfiddle.net/ytynqhmj/

A: By default ul element take padding-left: 60px; just update it with 0px to resolve this issue. Check updated snippet below..

html,
body {
    height: 100%;
    background-color: #333;
}

body {
    background-color: #333;
    text-align: center;
    text-shadow: 0 .05rem .1rem rgba(0, 0, 0, .5);
    margin: 0;
    font-family: "Helvetica Neue", Arial, sans-serif;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    display: block;
}

/** CONTAINER DIVS **/

.site-wrapper {
    display: table;
    width: 100%;
    height: 100%;
    min-height: 100%;
}

.site-wrapper-inner {
    display: table-cell;
    vertical-align: top;
    overflow: auto;
}

.logo-holder {
    height: 150px;
    text-align: center;
    border: 1px solid black;
}

.logo-holder h3 {
    line-height: 150px;
}

.nav-container {
    width: 300px;
    float: left;
    background-color: #fff;
    height: 100%;
}

.nav-container a {
    text-align: left;
    padding: 5px;
    color: #333;
}

.nav-container ul {
    width: 100%;
    padding: 0px;
}

.nav-container ul li {
    list-style-type: none;
    width: 100%;
}

.nav-container li:hover {
    background-color: #333;
}

Logo

Home

Blog

Store

Contact

A: Just remove default left padding for ul like this:
.nav-container ul{
  padding-left:0;<----Added
  //more code....
}

Demo

A: ul elements have a left padding by default.
Add padding: 0; or padding-left: 0; to .nav-container ul to avoid this
https://jsfiddle.net/ejzL9zo9/


text:
Q: Как обратиться к выведенному через AJAX запрос элементу массива с картинками? Есть полученные и отсеянные картинки с API через AJAX, которые мы выводим по первой кнопке. Нужно теперь иметь возможность выводить картинку по второй кнопке в блок ниже по айди записанном в input. AJAX запрос в отдельном файле лежит (отметил в коде). Подойдёт всё от native до промисов или что то актуальнее, не так давно учу JS интересно узнать как это решается!

// script.js
const resultBlock = document.querySelector('#result')
const pageNumberEl = document.querySelector('#page-number')
const clickMeButton = document.querySelector('#click-me')
const clickMeButton2 = document.querySelector('#click-again')
let idNumber = document.querySelector('#id-number')

clickMeButton.addEventListener("click", () => {
  getImages(pageNumberEl.value, onDataReceived);
})

function onDataReceived(data) {
  el = data.slice(0, 10)
  el.forEach(el => {
    const img = document.createElement("img");
    img.src = el.thumbnailUrl;
    document.querySelector('#result').appendChild(img);
  })
}
// server.js

function getImages(pageNumber, successCallback, onImageChoosed) {
  $.ajax(`https://jsonplaceholder.typicode.com/albums/1/photos`, {

    success: function(data) {
      successCallback(data);
    }
  })
}
<!doctype html>

  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="master.css">
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">

  <button id="click-me">ClickMe</button>
  <input id="page-number" value="1">

  <button id="click-again">ClickAgain</button>
  <input id="id-number" value="">


text:
Q: Why are the zero stretch and shrink in the definition of \z@skip explicit? Why do both The TeXbook and latex.ltx define \z@skip=0pt plus0pt minus0pt?  Wouldn't \z@skip=0pt or perhaps \z@skip=0pt\relax be shorter and yield the same?   I always thought that the stretch and shrink are zero by default.

A: In plain.tex we see
\newskip\z@skip \z@skip=0pt plus0pt minus0pt
\newbox\voidb@x % permanently void box register

If it had been
\newskip\z@skip \z@skip=0pt
\newbox\voidb@x % permanently void box register

then TeX would proceed to expand \newbox and lose time just to put back tokens. And it would need the knowledge of what the expansion of \newbox is anyway.
The alternative
\newskip\z@skip \z@skip=0pt\relax
\newbox\voidb@x % permanently void box register

would avoid the expansion and produce the same result, at the expense of clarity.
In latex.ltx the part is a straight copy from plain.tex.


text:
Q: Need to redirect to sign-oidc page after logout In Client application i have set below configuration and in postLogoutRedirectUri parameter set as sign-oidc url but still able to redirect to singin-oidc url and Auth service i have used using ADFS , openid connect and identity server using .Net 6.
 config: {
        authority: 'https://localhost:6001',
        clientId: 'Test',
        **postLogoutRedirectUri: 'http://localhost:6269/signin-oidc',**
        redirectUrl:'http://localhost:6269/signin-oidc',
        scope: 'openid profile',
        responseType: 'code',
        autoUserInfo: true,
        silentRenew: true,
        useRefreshToken: true,
        logLevel: LogLevel.Debug
      },

how can i redirect to signin-oidc page ?

A: You need to enable both frontchannel_logout support and session supported to true.
Example:
Here
Then make sure your ADFS Server implements the allow url by
Set-AdfsClient -TargetIdentifier <id> -LogoutUri http://localhost:5000/logout

If this is a server application
Set-AdfsServerApplication -TargetIdentifier <id> -LogoutUri http://localhost:5000/logout

So you can change your URL to something like this
https://localhost:6269/adfs/oauth2/logout?id_token_hint=<current_Id_Token>&post_logout_redirect_uri=http://localhost:6269


text:
Q: Contar cuántas variables estan vacias con PHP Buenas tardes necesito su ayuda, tengo que hacer una consulta en mi base de datos y para esto tengo que identificar cuantas variables estan vacias, por ejemplo tengo las siguientes variables:
$a,$b,$c,$d

de estas variables tengo que contar cuántas están vacías, he buscado pero aún no encuentro solucion, espero me puedan ayudar

A: Puedes usar el método empty()
if (empty(variable)) {
    echo 'variable es o bien 0, vacía, o no se encuentra definida en absoluto';
}


text:
Q: Detect specific sound in audio I have a short (~1 second) arbitrary sound file and two devices. At some unknown time, device 1 will play the sound file out of its speaker. Device 2 should then be able to detect that sound. There may be background noise. It's unknown how loud the sound will be played.
This feels like it should be a common solved problem, but searching for answers has left me with nothing.
If anyone has good a solution or could just point me in the right direction I'd be very grateful.

A: In most distance measurement and room impulse response measurement cases researches use Maximum length sequence (MLS) or sine sweep signals. These signals are played back and recorded. The recorded audio is used along with the inverted original signal to identify the presence of the played back audio. These MLS and sine sweep signals are very robust even in noisy environment. Each of them have their own advantages.
A similar method of playing back sound in a device and hearing it from another device is done by the microsoft guys to measure the distance between the devices-  http://research.microsoft.com/en-us/projects/BeepBeep/
You can play around with the MLS sequence using this MATLAB package http://www.commsp.ee.ic.ac.uk/~mrt102/projects/mls.html


text:
Q: Generic parameter 'T' could not be inferred with closures I have a static function below that will perform a GET request and then attempt to parse the data into whatever <T> is.
public static func get<T>(url: NSURL, paramaters: [String : AnyObject]?, paramaterEncoding: ParameterEncoding, compleation:(response: Response<T>) -> Void)

My question is how do I call it?
If I attempt to call it like below I get the error of Cannot explicitly specialize a generic function
let url = NSURL(string: "http://g.co")!
typealias JsonResponse = [String : AnyObject]
Notwork.get<JsonResponse>(url, paramaters: nil, paramaterEncoding: ParameterEncoding.json) { (response) in }

From looking around functions like these normally get their type from the variable that the function returns to just like the example below.
let result: Response<JsonResponse> = Notwork.get(url, paramaters: nil, paramaterEncoding: .json)

However as the result comes back in a closure, how do I specify what <T> is?
Thanks

Edit
Below is some sample code that depicts the same problem.
import Foundation

struct My {
    static func function<T>(compleation:(response: T) -> Void) {

        let apiResponse = ["some" : "value"]

        guard let value = apiResponse as? T else {
            return
        }

        compleation(response: value)
    }
}

//Gives error "Generic parameter 'T' could not be inferred"
My.function { (response) in

}

A: You need to explicitly tell the type when calling the function. If you are expecting String then call it with String type.
MyClass.myFunction { (response: String) in

}


text:
Q: The nodemailer connection is forcibly closed in Heroku after 5 min I'm using nodemailer library as an SMTP client to send emails outside. I'm also using the option for connection pooling that keeps socket open in the air for 10 min. After the 10 min of inactivity the socket is closing.
smtpClient = nodemailer.createTransport({... pool:true ...});
This is how it looks like when the connection is closing the regular way after the timeout event:
{ component: 'smtp-connection', sid: 'cHH7rJsPKGc' } Timeout
{ component: 'smtp-pool', err: { Error: Timeout
       at SMTPConnection._onTimeout (/app/node_modules/nodemailer/lib/smtp-connection/index.js:847:30)
       at TLSSocket.SMTPConnection._onSocketTimeout (/app/node_modules/nodemailer/lib/smtp-connection/index.js:199:44)
       at TLSSocket.emit (events.js:314:20)
       at TLSSocket.EventEmitter.emit (domain.js:483:12)
       at TLSSocket.Socket._onTimeout (net.js:484:8)
       at listOnTimeout (internal/timers.js:554:17)
       at processTimers (internal/timers.js:497:7)
     code: 'ETIMEDOUT',
     command: 'CONN' }, tnx: 'pool', cid: 1 } Pool Error for #%s: %s
{ component: 'smtp-connection', sid: 'cHH7rJsPKGc', tnx: 'smtp' } Closing connection to the server using "%s"
{ component: 'smtp-pool', tnx: 'connection', cid: 1, action: 'closed' } Connection #%s was closed

When running it on Heroku, it doesn't reach the 10 min but closes after the 4-5 min with an error:
{ component: 'smtp-pool', err: { Error: Unexpected Response: 451 4.7.0 Timeout waiting for client input [xxx.prod.protection.outlook.com]
        at SMTPConnection._processResponse (/app/node_modules/nodemailer/lib/smtp-connection/index.js:945:34)
        at SMTPConnection._onData (/app/node_modules/nodemailer/lib/smtp-connection/index.js:749:14)
        at TLSSocket.SMTPConnection._onSocketData (/app/node_modules/nodemailer/lib/smtp-connection/index.js:195:44)
        at TLSSocket.emit (events.js:314:20)
        at TLSSocket.EventEmitter.emit (domain.js:483:12)
        at addChunk (_stream_readable.js:298:12)
        at readableAddChunk (_stream_readable.js:273:9)
        at TLSSocket.Readable.push (_stream_readable.js:214:10)
        at TLSWrap.onStreamRead (internal/stream_base_commons.js:188:23)
      code: 'EPROTOCOL',
      response: '451 4.7.0 Timeout waiting for client input [xxx.prod.protection.outlook.com]',
      responseCode: 451,
      command: 'CONN' }, tnx: 'pool', cid: 2 } Pool Error for #%s: %s
{ component: 'smtp-pool', tnx: 'connection', cid: 2, action: 'closed' } Connection #%s was closed
{ component: 'smtp-connection', sid: 'Wabdmex9scE', tnx: 'network' } Connection closed

Just to remind, the nodemailer uses Node.js tls.connect() to open a socket:
this._socket = tls.connect(opts, () => {
   this._socket.setKeepAlive(true);
   this._socket.setTimeout(10 * 60 * 1000);
});

Node.js version: "12.15.0"-"12.19.0"
nodemailer version: "^6.1.1"


text:
Q: Extract token from a curl request and use in another shell command I've started picking up bash scripting and I'm stuck at something I'm trying to wrap my head around.
I have a curl command that outputs a token and I need to use it in the following command:
curl -k 'https://server:port/session' -X POST -H 'Content-Type: application/json' -d '{"username":"admin","password":"password"}'

It then outputs a token here:
{"token":"ac07098ad59ca6f3fccea0e2a2f6cb080df55c9a52fc9d65"}

I then need to use it in the follow up command
curl https://server:port/ -k -X POST -H 'Content-Type: application/json' -H 'X-Cookie:token=token' -d '

I was thinking I could output the token to a file, then have a sed command write the token to a file, then the new command use a variable where token=$token
Thanks!

A: This is where a JSON parsing tool comes in handy (such as jq):
$ echo '{"token":"ac07098ad59ca6f3fccea0e2a2f6cb080df55c9a52fc9d65"}' | jq -r .token
ac07098ad59ca6f3fccea0e2a2f6cb080df55c9a52fc9d65

So
json=$( curl -k 'https://server:port/session' -X POST -H 'Content-Type: application/json' -d '{"username":"admin","password":"password"}' )
token=$( jq -r ".token" <<<"$json" )

curl https://server:port/ -k -X POST -H "X-Cookie:token=$token" ...

A: With no further tool than a bash (tested Centos/Rhel7/GitBash) :
json=$(curl -k 'https://server:port/session' \
            -X POST -H 'Content-Type: application/json' \
            -d '{"username":"admin","password":"password"}') \
&& token=$(echo $json | sed "s/{.*\"token\":\"\([^\"]*\).*}/\1/g") \
&& echo "token = $token"

then use your authentication needing commands like that :
curl https://server:port/ -k -X POST \
                          -H 'Content-Type: application/json' \
                          -H 'X-Cookie:token=$token' -d ...'

A: If Python is installed, and hopefully it is on modern systems, you can do something like:
OUTPUT="$(curl -k 'https://server:port/session' -X POST -H 'Content-Type: application/json' -d '{"username":"admin","password":"password"}' | python -c "import sys, json; print json.load(sys.stdin)['token']")"

This will give you:
echo $OUTPUT
ec2e99a1d294fd4bc0a04da852ecbdeed3b55671c08cc09f

A: Use the `` syntax:
cmd1result=$(command1 | cut -d ':' -f 2 | grep -Po "[a-z0-9-]+")
command2 $cmd1result


text:
Q: Insert to tableViewCell when button pressed in another view controller Im new to programming and trying to build my own app, I wonder how Im I supposed to link the info I get from the addTask viewcontroller to the tableview cell? At the moment Im just trying to get the text from the textfield and Im going to add the other features later.
What Im trying to do

A: Refer This :-
Create a global array add remove element from that array on click of your button

A: You can pass data from one view controller to another using Delegates. Check my ans here. You can set your table view class as delegate of your task view controller. Implement the protocol methods of task view controller get the data and reload table.
Hope it helps.
Happyy Coding!!

A: You can pass data using Delegation .
In Second ViewController
import UIKit

protocol secondViewDelegate: class {
   func passData(arrData : [Any])
   }

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    weak var delegate: secondViewDelegate? = nil

        @IBAction func clickOnButton(_ sender: Any) {
            self.delegate.passData([]) // replace your array here
         }
}

In FirstViewController
class FirstViewController: UIViewController, UITableViewDataSource, secondViewDelegate

    let objectSecondVC: SecondViewController? = storyboard?.instantiateViewController(withIdentifier: "secondVCID") as! SecondViewController?
            objectSecondVC?.delegate = self
            navigationController?.pushViewController(objectSecondVC?, animated: true)

Second ViewController Delegate Method in FirstViewController
func passData(arrData : [Any]){
// append to your main array
}

A: It seems like your add task view controller is connected with your table view controller though a segue. So when you moving back from add task view controller, you can use unwind to pass data back. Here is a detailed tutorial with simple instructions and pictures.


text:
Q: Telnet ip address at a given port What's the difference between:
C:>telnet somehost 25

and
C:>telnet
Microsoft Telnet>open somehost 25

Why in the first case I immediately get a new completely black prompt, while the second case remain freezing to:
Connecting to host...

Help me.

A: There is no difference. Try telnet /? and the help command from inside telnet.
What you can see on the screen in the second case is just because launching a command from the telnet prompt has more verbosity.


text:
Q: changing output of the console.WriteLine During my job interview, interviewer asked me to change the the console output to print "B" without touching the main method and console!
is this possible? (I tried to change the entry point,but it was not correct)
I have no idea how to answer this question
 class Program
  {
        static void Main(string[] args)
        {
            Console.WriteLine("A");
        }
  }

A: Well, your interviewer said you can't touch the console. He didn't say you can't make a new one.
public static class Console
{
    public static void WriteLine(string dontCare)
    {
        //Specify System.Console instead of just Console
        System.Console.WriteLine("B");
    }
}

public static class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("A");
    }
}

Alternatively, you can go through with your idea, which was to make a new Main method, which prints "B" to the console. For that to work, you just have to tell the compiler which one to actually use. This thread details several ways of doing that.


text:
Q: Can snappy be used with Redis After I compressed data by Snappy, and then stored it to Redis. But When I took it out of Redis, I found the data is different. I don't know why it is

A: Yes, Snappy compression algorithm can be used with Redis. In fact, you can use any compression algorithm. As far as Redis is concerned, it is just bytes. What redis calls as "Strings" is more traditionally called as "byte array" in programming languages.
If you are seeing different values, it is most likely a problem with the way you are reading values. Some redis client libraries try to decode the response as UTF-8, and that isn't what you want it to do. Look at your client library documentation, and use the method that lets you set and get values as byte arrays.

A: Yes is the answer. If your problem is on java. You can check this repo here, with what i had done for compression and serialization java-spring-redis-compression-snappy-kryo
java-spring-redis-compression-snappy-kryo
Here is a sample of a Java Spring Boot Redis Cluster Data configuration.
It is an implementation with Redis Cluster and Redis Cache Manager.

*

*Snappy Compression

*Kryo Serialization

*Support ttl per cache key
Gradle configuration

*

*spring-data-redis

*lettuce-core

*snappy-java

*kryo

*commons-codec

Application Properties
data.rediscluster.nodes=redis1.foo.com:6379,redis2.foo.com:6379,redis3.foo.com:6379,redis4.foo.com:6379,redis5.foo.com:6379,redis6.foo.com:6379

data.rediscluster.ttl=2700

data.rediscluster.redirects=3

How to use it
 RedisCacheConfiguration.defaultCacheConfig()
.disableKeyPrefix()
.disableCachingNullValues()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(genericSnappyRedisSerializer()))
.entryTtl(Duration.ofSeconds(ttl));


text:
Q: How can I re-hide previously hidden files? Previously I used attrib -s -h -r /s /d to un-hide all hidden files in D:\.
How can I re-hide the previously hidden files that are hidden by default? Most of them are desktop.ini and Thumbs.db

A: You could make use of windows built in GUI for showing hidden files and folders.
Open Control Panel > click Appearance and Personalization > click Folder Options.
Click the View tab.
Under Advanced settings, click Show hidden files, folders, and drives.
Check/Uncheck the various options to hide/show files with the hidden attribute

A: At drive root, cmd:
attrib +s +h -r Desktop.ini /s
attrib +s +h -r Thumbs.db /s

These commands reset attributes for all Desktop.ini and Thumbs.db in a target drive you run the command from.
Be aware that it could take a while.
It only resets file properties but will not change your Explorer settings. Hidden system files are hidden by default but can be changed to always show by user.


text:
Q: Mocking constructor to force my way into a conditional So I'm doing unit testing and I need to make it into a conditional based upon the below condition (i.e I want the condition to be true)
if(foo.body.constructor === Object && Object.keys(foo.body).length === 0) {
.
.
.
}

My mock up looks like this so far.  This doesn't crash but it won't go into the conditional as I would like.
let foo = {
    body:()=> jest.fn()
}

I've also tried the below and noticed that the length returned is always 1.
let foo = {
        body:{
            constructor: Object
        }
    }

Not sure what I need to do to get the length of foo.body to be 0 as well as have the foo.body.constructor be 0

A: The two conditions are that foo.body is an Object and that foo.body does not have any keys, so this will get you inside the conditional:
const foo = {
  body: {}  // Object with no keys
};

A: let foo = {
  body: {
    aMockedKey: () => jest.fn()
  }
}

The second condition is testing keys of foo.body


text:
Q: Remove session in url - Laravel I would like to remove the laravel_session in the url:
The first time when I come on the site, it appears but when I click on an another link, it disappears.
I would like to remove it when I just come on the site.
I have something like this: index?laravel_session=9bujan8gjmbtfb1qig6rju23c5
I try to change the session drive of Laravel. I try to put it on "array",but it removes the laravel_session however sessions are not persisted.
Currently, I use 'cookie'.

A: This isn't a laravel issue, this is a php config issue. See this page http://www.php.net/manual/en/session.idpassing.php
You can change it by adding the following line to your bootstrap code
ini_set('session.use_trans_sid', false);

or by editing .htaccess and adding the following line to the top of the file
php_value session.use_trans_sid false

or by editing php.ini if you are able
All in all if you can't edit the php.ini file the .htaccess method is cleaner.


text:
Q: Sending sms using AWS sns outside sandbox, still need to verify the new phone number first? I keep looking for the informaion on AWS SNS services of SMS.
I would like to make sure the question before I request AWS account being moved out of the SMS sandbox.
I am trying to use this services on a product running on Heroku, which means I have to use the region on US East (N. Virginia) us-east-1. But the product users mainly live in Asia. I test it in sandbox mode, and it can receive the message.
Here comes the question:
If AWS account exits SMS sandbox and try to send SMS to a new phone number, do I still need to verify the phone number first then it can receive the message?
I read those two document, but cannot ensure the services. Really appreciate any answers to help me figure out.

*

*[1] https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html

*[2] https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox-moving-to-production.html

A: You do not need to verify phone numbers you wish to send SMS messages to once you have exited the SMS sandbox. This is strictly a requirement for accounts in the SMS sandbox.

A: You can test it in CLI and then in you app

*

*get the number of your client in app

*put the value in this sintaxe:
aws sns create-sms-sandbox-phone-number --phone-number

*ask the customer for the code and put it in this syntax
aws sns verify-sms-sandbox-phone-number --phone-number  --one-time-password

*send it
aws sns publish --message "Hello friend, you are subscribed!" --phone-number
IN CLI:
aws sns create-sms-sandbox-phone-number --phone-number <value>
aws sns verify-sms-sandbox-phone-number --phone-number <value> --one-time-password <value>
aws sns publish --message "Hello friend, you are subscribed!" --phone-number <value>

IN APP:
>>> import subprocess
>>> subprocess.run(['aws','sns', 'publish', '--message', '"Hello, world!"', '--phone-number', '+5511123456789'])


text:
Q: Javadoc: error - Cannot find doclet class I'm trying to run Javadoc with a custom doclet from windows command line:
javadoc -classpath C:\path\to\build\dir -sourcepath C:\path\to\src\dir -doclet somePackageName.customDocletClassFileName anotherPackageName

"anotherPackageName" is the package directly under given sourcepath for which I want to produce documentation.
When I execute it like this I get the error:
javadoc: error - Cannot find doclet class somePackageName.customDocletClassFileName

It seems like there is something wrong with the -classpath flag, any ideas?
If I substitute
-doclet somePackageName.customDocletClassFileName

to
-docletpath somePackageName

it works better (although I cannot really verify the output since I have not added the testng jar to the classpath and then there's a lot of other issues).

A: SOLUTION:
-classpath is not used for finding doclets, instead -docletpath should be used, i.e:
javadoc -classpath C:\path\to\build\dir -docletpath C:\path\to\build\dir -sourcepath C:\path\to\src\dir -doclet somePackageName.customDocletClassFileName anotherPackageName

(Thanks to a colleague)


text:
Q: Creating a ZIP file in memory with System.IO.Packaging.Package Currently i'm trying to create a zip-file within my memory. I collect many files
byte[] item1 = File.ReadAllBytes(@"C:\1.gif");
byte[] item2 = File.ReadAllBytes(@"C:\2.gif");

and in a second step I want to add them to one zip file and save that zip file
byte[] result = AddFilesToZip(new byte[][] { item1, item2 });
File.WriteAllBytes(@"C:\images.zip", result);

Here is my approach AddFilesToZip:
public static byte[] AddFilesToZip(byte[][] filesToAdd)
{
    using (System.IO.MemoryStream result = new MemoryStream())
    {
    using (System.IO.Packaging.Package zip = System.IO.Packaging.Package.Open(result, System.IO.FileMode.Create))
    {
        for (int i = 0; i < filesToAdd.Length; i++)
        {
            System.IO.Packaging.PackagePart ZipPart = zip.CreatePart(new Uri(i + ".gif"), MediaTypeNames.Application.Zip, System.IO.Packaging.CompressionOption.Normal);
            ZipPart.GetStream().Write(filesToAdd[i], 0, filesToAdd[i].Length);
        }
    }
        return result.ToArray();
    }
}

But I already get an error, that URI is invalid at new Uri(i + ".gif").

Invalid URI: The format of the URI could not be determined.

A: The issue seems to be that you will need a relative URI, but the Uri class doesn't know what kind of Uri you're creating.
Try this instead:
new Uri("/" + i + ".gif", UriKind.Relative)


text:
Q: sql update based on count I have a stored procedure that creates 4 temp tables and then returns records with a big select with inner joins at the end.  This is a cut-down version of the select that returns records.
SELECT R.*,
    REC.Status_Date as [Receive Status Date],
    RET.Status_Date as [Return Status Date]
FROM    #Records R
    INNER JOIN #Temp_Receive REC ON R.ID1 = REC.ID1
    INNER JOIN #Temp_Return RET ON R.ID1 = RET.ID1
    INNER JOIN #Temp_Submittal SUB ON SUB.RecID = REC.ID AND SUB.RetID = RET.ID

Note that there may be multiple #TEMP_Receive and #TEMP_Return records for the same ID1 and the #TEMP_Submittal table is what connects them.
I need to modify this procedure to include the number of holidays between the two status dates in two different tables that are included in the results. I can count the number of holidays from a separate table.  Something like this:
Select count(*)
From Holiday_List
Where Holiday_Date between REC.Status_Date and RET.Status_Date

I added a column Holiday_Count to the #Temp_Receive table.  How can I update the Holiday_Count column in the join with the count from the Holiday_List table?  I've tried something like this but from what I can find, this isn't remotely valid SQL syntax.
UPDATE
(   #Records R
    INNER JOIN #TEMP_Receive REC ON R.ID1 = REC.ID1
    INNER JOIN #TEMP_Return RET ON R.ID1 = RET.ID1
    INNER JOIN #TEMP_Submittal SUB ON SUB.RecID = REC.ID AND SUB.RetID = RET.ID )
SET REC.Holiday_Count =
( SELECT COUNT(*)
  FROM HOLIDAY_LIST HOL
  WHERE HOL.HOLIDAY_DATE between #TEMP_Receive.Status_Date AND #TEMP_Receive.Status_Date )

I'm running MS SQL Server 2012.

A: 1) Try to build select statement to see which rows will be updated. In your case the query may look like this.
SELECT R.*,
    REC.Status_Date as [Receive Status Date],
    RET.Status_Date as [Return Status Date],
    (Select count(*)
        From Holiday_List
        Where Holiday_Date between REC.Status_Date and RET.Status_Date) cnt
FROM    #Records R
    INNER JOIN #Temp_Receive REC ON R.ID1 = REC.ID1
    INNER JOIN #Temp_Return RET ON R.ID1 = RET.ID1
    INNER JOIN #Temp_Submittal SUB ON SUB.RecID = REC.ID AND SUB.RetID = RET.ID

2) When everything looks OK then replace select part with update statement.
update #Temp_Receive
    set Holiday_Count = (Select count(*)
        From Holiday_List
        Where Holiday_Date between REC.Status_Date and RET.Status_Date)
FROM    #Records R
    INNER JOIN #Temp_Receive REC ON R.ID1 = REC.ID1
    INNER JOIN #Temp_Return RET ON R.ID1 = RET.ID1
    INNER JOIN #Temp_Submittal SUB ON SUB.RecID = REC.ID AND SUB.RetID = RET.ID

Also note that multiple inner join implicitly suggest that same ID1s exist in all 4 tables.


text:
Q: Swift 2.2 : Decimal conversion not working as expected in Xcode Trying to convert string to decimal and shows unexpected values for some strings such as 8.80 and 9.80 , tried to run some code in playground and Xcode, please refer below screen shots. I suspect this as a apple bug, Any suggestions why does the Double append zeros to some values ?
Also i have noticed using print you get expected value, but the variable is actually holding the big value with appended zeros, please refer screen shot, I still consider this as a bug.
var totalStr = "8.80"
var total = Double(totalStr)


text:
Q: How to pass xsi type of parameter in PHP SoapClient I am trying to consume soapclient based API of https://developer.signicat.com/documentation/signing/get-started-with-signing/full-flow-example/
There are tow methods of it
1- you have to upload a document and it returns you an SDS ID, this part works fine
2- then you need to use this SDS ID in second part of API to create a sign request method name is createRequest(),
This is where I am getting problem, I have passed all the parameters but still getting an error on one parameter which is xsi:type I am not sure how to pass this parameter from php array.
Here is the sample XML
 <document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ref-sds-id="090520195vbxk9uuw4dks9tjm2pmpy7sx3na397xz6qclxtepaslnb00q7" send-to-archive="false" xsi:type="sds-document">
                        <sign-text-entry/>
                        <description>Loan contract.pdf</description>
                    </document>

here xsi:type="sds-document" this part is causing the issue
My Code:
    $url = 'https://preprod.signicat.com/ws/documentservice-v3?wsdl';

    $soap_setting = array(
            "trace" => 1,

            'features' => SOAP_SINGLE_ELEMENT_ARRAYS + SOAP_USE_XSI_ARRAY_TYPE
        );

    $client = new SoapClient($url,$soap_setting);

    $subject_type = $client->__getTypes();
    $functions = $client->__getFunctions();

    $subject = array(
        'national-id'=> '198003010306',
        'first-name'  => 'Oskar',
        'last-name'   => 'Johansson',
        'email'       => 'kamran@creativerays.com'
    );

    $notification = array(
        'recipient' => 'http://localhost/sign/php/',
        'type' => 'URL',
        'message' => 'Please seign ${taskUrl}',
        'header'=> 'Test',
        'notification-id' => '001'
    );
    $sdsdocument = array(
        'ref-sds-id' => '100520193oz5vev0onyueul43ury4vz8g1hsnhr7w69pcwnoan96ojbtbb',
        'send-to-archive' => true,
        'description'=> 'test',
        'sign-text-entry'=> 'test',
        'xsi:type' => 'sds-document'

    );
    $documentaction = array(
        'document'=> $sdsdocument,

        'type'=> 'sign',
        'optional'=> true,
        'send-result-to-archive'=> true
    );
    $tasks = array(
        'subject'=> $subject,
        'document-action'=> $documentaction,
        'notification'=> $notification,
        'on-task-postpone'=> 'http://localhost/sign/php/?requestId=${requestId}&taskId=${taskId}&status=taskpostponed',
        'on-task-complete'=> 'http://localhost/sign/php/?requestId=${requestId}&taskId=${taskId}&status=taskcomplete',
        'on-task-cancel'=> 'http://localhost/sign/php/?requestId=${requestId}&taskId=${taskId}&status=taskcancelled',
        'configuration'=> 'default',
        'signature' =>array('method'=>'nbid-sign'),
        'id'=> 'task00001',
        'bundle'=> False
    );

    $request = array(
        'language'=> 'en',
        'task'=> $tasks
    );

    $tparam = array(
        'service'=>'demo',
        'password'=>'Bond007',
        'request' =>$request
    );

    $create = $client->createRequest($tparam);
    echo '<pre>';
    print_r($create);
    echo $client->__getLastRequestHeaders();
    echo '</pre>';

The Error I am getting:
Fatal error: Uncaught SoapFault exception: [soap:Client] Failed to register new document action request: Document with id null must have subtype archive-document, sds-document, result-document, upload-document or provided-document


text:
Q: Attaching files in signature by default on gmail I notice that people sometimes send emails with their vcards attached. How are they doing this, and is there any way to do it on gmail?
Thanks SOCommunity!

A: This site will help you create a file - you just attach that to your email.
For corporate mail, this Exchange signatures software can do it for all users.


text:
Q: "reset the north direction of my life" meaning
The 7 habits have taught me profound truths that transcend because they are based on principles. They have helped me see what I cannot see.  In every situation I can use the principles and paradigms associated with each habit, think over and reset the north direction of my life.

The phrase seems to be used metaphorically, but I'm not sure what it means exactly.  Is "the north direction" referring to the right direction?


text:
Q: Handling User Defined shaders in OpenGL ES 2.0 framework I am developing a frame-based animation framework in OpenGL ES 2.0 to develop 3D graphics applications.
I have used few pre-defined shaders (for color, texture, alpha....) whose attributes and uniform are known.
Now I want to handle user given shaders. Loading, compiling and linking these shaders are fine.
But how to map the attributes and uniforms to its corresponding data.
Suppose, in the user given shader, the vertex data has to be passed to attribute "a_vertex".
In some other shader, it may be "a_myVertex".
Thus name of the attribute to pass vertex data will be different for different user given shaders.
My question is how to handle the mapping of shader attributes and uniforms in the user given shaders.
Please give some suggestions to do this.
Thanks...


text:
Q: Explorer not loading files and previews First of all, I hope not to post something it has been already asked because it's really hard to search for something like this. My problem has been going on since I installed Windows 10 for the first time (as soon as I saw the free update from 8.1) and I said to myself "Well, they will fix this in the future so let's wait". Years have passed but this problem is still here and it's becoming really annoying so I decided to ask for a solution. Many things happen and it is difficult to describe so, to simplify, I will make a list of the events that happen:
1) I'm surfing files with the explorer and, at some point (this is random, don't really know when it could happen) the explorer literally starts not showing previews of files (usually when I enter a folder full of images or movies) in every folder.
2) When this happens, if I close the explorer window and I open it again a can't see anything. No files, no settings, nothing. Just an infinite loading; here's a pic of what I mean:

3) To make it work again I have to open an explorer window, then open the task manager and reboot the explorer process. Doing this, I'm able to surf "simple" folders (like documents, or the root folder where I can see my HDDs) but If I come back on that directory full of files everything crash again.
4) If I reboot my computer, the explorer returns to work without problems and I also can enter that difficult folder. I don't know, maybe it's a continuous entering/exiting from certain folders that make it crash.
5) I already tried to clear the explorer chronology, I reinstalled Windows many times; no viruses, no strange problems solvable with an sfc scannow.
I would be really glad if you can help me with this, I'm at my wit's end. Thanks for now and sorry If I made mistakes with the English language.

A: The infinite loading screen in the File explorer is usually the result of the a failure in creating thumbnails or similar errors.
Try the following solutions,
Solution 1: Restarting Process

*

*Open the task manager.

*You will find a background process named COM Surrogate.

*Right click on the process and click End Task.

This background process is responsible for creation of Thumbnails.
Solution 2: Clearing Thumbnail Cache
If the first solution did not work for you try this.

*

*Open File Explorer.

*Right-click the drive where Windows 10 is installed (usually C:), and select Properties.

*Click the Disk Cleanup button.

*Check the Thumbnails option, and uncheck all the other options.

*Click OK and then click Delete Files.

Reference:

*

*How to reset thumbnail cache


text:
Q: Does lightning have a thickness? We have calculated (probably measured) the speed, temperature and voltage of lightning so does lightning have a thickness?
Note:
When a lightning occur it heats up the air rapidly causing the air to become plasma, I'm not referring to the thickness of ionized air.

A: The primary "bolt" of lightning carrying the most current is only a few centimeters across.  However, the entire "tube" that is carrying a significant current can be upwards of 10 meters across.  If the lightning hits the ground, the current spreads out across the surface in all directions (not necessarily uniformly) increasing the radial extent of danger.  This is one of the many reasons why you need not be hit by the main bolt to still be struck by lightning.