text:
Q: how to get the timestamp with timezone in rust I am using this rust code to get the timestamp, but the time without time zone:
use std::time::Duration;
use chrono::{DateTime, FixedOffset, Local, NaiveDateTime, TimeZone, Utc};
use diesel::sql_types::Timestamptz;
use rust_wheel::common::util::time_util::get_current_millisecond;
use tokio::time;

#[tokio::main]
async fn main() {
    let trigger_time = (get_current_millisecond() - 35000)/1000;
    let time_without_zone = NaiveDateTime::from_timestamp( trigger_time ,0);
}

the timestamp result is 2022-08-30 13:00:15, the actual wanted result is: 2022-08-30 21:00:15. Then I tried to set the timezone:
use std::time::Duration;
use chrono::{DateTime, FixedOffset, Local, NaiveDateTime, TimeZone, Utc};
use diesel::sql_types::Timestamptz;
use rust_wheel::common::util::time_util::get_current_millisecond;
use tokio::time;

#[tokio::main]
async fn main() {
    let trigger_time = (get_current_millisecond() - 35000)/1000;
    let time_without_zone = NaiveDateTime::from_timestamp( trigger_time ,0);

    let tz_offset = FixedOffset::east(8 * 3600);
    let date_time: DateTime<Local> = Local.from_local_datetime(&time_without_zone).unwrap();
    print!("{}",date_time);

    let dt_with_tz: DateTime<FixedOffset> = tz_offset.from_local_datetime(&time_without_zone).unwrap();
    print!("{}",dt_with_tz);
}

the result is 2022-08-30 13:00:15 +08:00. is it possible to get the timestamp with the timezone? what should I do? I mean get the timestamp format like this 2022-08-30 21:00:15.

A:
the result is 2022-08-30 13:00:15 +08:00. is it possible to get the timestamp with the timezone? what should I do? I mean get the timestamp format like this 2022-08-30 21:00:15.

Your timestamp is (I assume) UTC, so that's what you should tell Chrono:
    let time_without_zone = NaiveDateTime::from_timestamp(timestamp, 0);
    // 2009-02-13 23:31:30
    let zoned: DateTime<FixedOffset> = DateTime::from_utc(time_without_zone, FixedOffset::east(8 * 3600));
    // 2009-02-14 07:31:30 +08:00

Then you can use naive_local() to get a naive (timezone-less) view of the local time:
    zoned.naive_local()
    2009-02-14 07:31:30

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=941668e1e10930b0e9a6ede7e79fb0c1
Warning: I'm not entirely sure naive_local() is the correct call, normally in chrono the "local" timezone is the timezone configured for the machine the program runs on (or something along those lines), but for naive_local it seems like chrono just applies the timezone and returns the result as a naive datetime. So it's what you want, but I find it a bit dubious. I can't find a better call tho.


text:
Q: Hadn't encounters with the Borg already occurred in the Neutral Zone prior to Q Who? In the episode Q Who, at the end, Guinan says that the encounter with the Borg happened before it should have. Picard says "they will be coming" in response to Guinan saying that they are now aware of The Federation's (or humanity's) existence implying this was the Borg's first contact with them as well.
However, earlier in the episode, after Q first sends the enterprise light years away, when scanning a Class M Planet Worf comments that the suspected industrialized civilization that had been there there appeared to have been ripped away from the planet identical to what happened to the outposts along the Neutral Zone in the episode The Neutral Zone.
This made me think that in both cases the perpetrators were the Borg and that the Federation and the Romulans have encountered the Borg already.....just that no one's survived to report back.
If that is the case then didn't the Borg already know about the Federation? If Guinan was expecting the Federation to encounter the Borg much later, was she not aware that the encounter had already happened and they are already seen as they are just raw material for the Borg?

A: YES
Borg encounters were known to Starfleet but the information was not generally known throughout the Federation.
From the Memory Alpha page on the Borg

As of "Q Who" and "The Best of Both Worlds", it appeared that Starfleet had never heard of the Borg. Subsequently, Star Trek: Enterprise's "Regeneration" and Star Trek: Voyager's "Dark Frontier" showed that not only was Starfleet previously aware of the existence of the Borg, Federation scientists actually pursued them – even if they were considered mere rumor. Further, although Guinan indicates in "Q Who" that her people were attacked by the Borg, it is implied that Starfleet was not aware of the threat. However, it was later revealed in Star Trek Generations that Starfleet, in fact, rescued the El-Aurian survivors of the Borg attack including Guinan, and it seems unlikely that Starfleet would not inquire as to the cause of their plight.

A: The Borg would have learned about humanity and the Federation when they assimilated Seven of Nine's parents in 2356.

A: If no one has survived to report the encounter then no one in the federation would know about the encounter and Guinan is in the federation.
If I remember correctly though the Borg do not rip planets apart they assimilate so if the Borg had attacked the M class planet they would still be present and assimilating biological and technological matter.

A: Actually, It depends on if you include the books, all the television series and the movies. Just based on the television series, in Star Trek Enterpise, borg are found on Earth frozen and they assimilate the researchers. Technically, that would be the first contact and the Borg drones would have found out about the federation then and they did transmit a signal. However, I believe, the person that wrote they were not interested in us due to our level of technology and the low threat level we posed to them was correct. Remember, the borg did not attack Capt. Archer's crew or Capt. Picard's crew until they deemed them a threat. If you include the books and movies, then in Shatner's series of books that take place after the movie Star Trek Generations, Kirk, Picard and Spock agree that the "Machine Beings" that repaired the Voyager space probe in sent it back to Earth in Star Trek I were the Borg. Of course, they sent it back before the Federation was created and the Voyager probe never called them by name. However, it had collected so much data and transmitted to Earth and the Enterpise so I am sure that there was some mention of them in that data to. This of course took place after Capt. Archer's Enterprise encountered them and chased them. The crew of Archer's Enterprise may have met them before that during the episode when the Enterprise needed major repairs and found the automated repair hanger that had the beings attached to a central computer that could repair itself and modify itself as needed. Let us think about the similarities, an artificially intelligent computer that abducts intelligent beings and connects them to itself (assimilation), can modify (adapt) itself to complete this, can repair (regenerate) itself, refuses to answer questions not relevent to the task at hand and refuses to discontinue operations when told to do so or threatened (resistance is futile). Anyone else notice any similarities. As for Guinan and her fellow survivors, the Federation did not get involved with them until after the attack and the Borg had left. Not sure if any of Guinan's people that were assimilated knew about the status of the Federation and its tech, but she did already know about Earth and about Picard since they had time traveled and stopped the alien beings from attacking and killing humans where the Enterprise crew met Samuel Clements (Mark Twain) and the younger version of Guinan. During the STNG series she mentions that her people are listeners and watchers so her people might have continued to visit Earth and thereby seen the development of the tech and the Federation and that knowledge could have been assimilated by the Borg in the attack mentioned in Star Trek Generations.

A: The Borg were in a different quadrant heading in the opposite direction from the federation in search mode the encounter with the enterprise. Q put the enterprise back in alpha quadrant which is why the federation was able to "prepare" for the Borg.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wrong serialization JSON in String field I'm developing app using QuickBlox services. I have String field with JSON in content. This is my JSON:
{"answers":[[{"name":"first"}],[{"name":"second"}],[{"name":"third"}],[{"name":"fourth"}],[{"name":"fifth"}],[{"name":"sixth"}]]}

Here is problem. When I want to get my field with JSON from QBCustomObject, it is serialized to this (without quotes and square braces):
[{
answers :
{
name : first
},
{
name : second
},
{
name : third
},
{
name : fourth
},
{
name : fifth
},
{
name : sixth
}
}]

What can I do in this situation?
I found in QBCustomObjectDeserializer class that code:
if(value.contains("[")) {
                String[] values2 = value.replace("[", "").replace("]", "").replace("\"", "").split(",");

Can I change rules of deserialization in QuickBlox SDK? Can I use my own deserializer?
Anyone can help resolve my problem please?

A: Fixed in development branch
https://github.com/QuickBlox/quickblox-android-sdk/tree/development
will be rolled out in our next upcoming release


text:
Q: Can you change the properties of an object even after adding it to the container? I have a GOval object lets call it circle which I am using in an applet. I added the GOval object to the container and then below the line where I added it to the container I typed the following lines of code in:
circle.setFilled(true);
circle.setFilledColor(Color.WHITE);

but I don't understand why this worked? Because I already added the circle to the container before these two lines so how is the circle getting filled with white color when my applet is displayed?
So does this mean that even the organization of the various objects into different layers like sending objects to back or bringing objects to front can be done after adding those respective objects to the container?

A: Container doesn't have copy of added object, but reference to original object, so you can change original object and see it in container when it is painted/repainted.

A: You created a variable called circle.  Or more correctly, you have a reference to a variable called circle.  (the variable points to the memory location of the variable)
When you add it to the container, the container now links to that memory address for that position in the container (let's say you had a basic array, position 0 in the array points to that memory address)
When you change the object at that memory address (regardless of whether you change it from your variable called circle, or container object 0)...the fact is, their pointing to the same memory location - same object!


text:
Q: Are these Apache vhost rewrites efficient? Our ecommerce system has about a 300 - 500 ms TTFB, which I don't think is bad at all, but still isn't as good as a static file. This week I finally experimented with creating my own local cache of product / category pages, and telling our server to rewrite to those files if available, else rewrite to the ecommerce system.
It works great and our TTFBs are usually around 50 - 100 ms now. I also watched our server load average in top and, for the most part, the numbers went from around 0.5 down to 0.2ish (with some occasional jumps due to traffic). So in general it looks like this is making the server run smoother as well as well as speed up page load time, which is what I hoped for.
That being said I'm no expert on rewrites and server performance - can anyone do a quick review and let me know if there's room for improvement? These rewrites are located in the vhost file.
# product pages
RewriteCond %{REQUEST_URI} ^/product_([^.]+).*$
RewriteCond %{DOCUMENT_ROOT}\/\local_http_cache\/product_%1.php -f
RewriteRule (.*) /local_http_cache/product_%1.php?CacheFlag [PT,QSA,L]
RewriteRule ^/product_([^.]+).*$ /path/to/OurEcommerceSystem?ProductID=$1 [PT,QSA]

# category pages
RewriteCond %{REQUEST_URI} ^/category_([^.]+).*$
RewriteCond %{QUERY_STRING} !((^|&)(Sort_By|Per_Page)=(.*)+(&|$))
RewriteCond %{DOCUMENT_ROOT}\/\local_http_cache\/category_%1.php -f
RewriteRule (.*) /local_http_cache/category_%1.php?CacheFlag [PT,QSA,L]
RewriteRule ^/category_([^.]+).*$ /path/to/OurEcommerceSystem?CategoryID=$1 [PT,QSA]

Couple of other notes:

*

*For both product and category pages the main goal is the same: check if a cache file exists for this product / category ID. If so, serve it, else do nothing and let the next rewrite send the request to our ecommerce system.

*The ?CacheFlag doesn't do anything particularly functional - but a rule in /local_http_cache/'s .htaccess file tells it to forbid anything that doesn't have that flag, so no one can browse those files directly

*the cache pages are purposely PHP due to some code that checks session IDs, but I'm going to look in to eliminating that, which would allow me to cache just static html code.

A:
RewriteCond %{REQUEST_URI} ^/product_([^.]+).*$
RewriteCond %{DOCUMENT_ROOT}\/\local_http_cache\/product_%1.php -f
RewriteRule (.*) /local_http_cache/product_%1.php?CacheFlag [PT,QSA,L]

You don't need the first condition that checks the REQUEST_URI. This check should be performed in the RewriteRule pattern instead (just as you have done for the directive that follows) - instead of using a generalised match anything (.*) (which didn't need to be capturing) in the RewriteRule. (You will naturally need to change the backreference from %1 to $1 if you do this - see below)
The RewriteRule pattern is processed first. Only if this matches are the preceding conditions processed, so by having a match everything pattern here, you are forcing the RewriteCond directive(s) to be processed.

^/product_([^.]+).*$

The trailing .*$ is superfluous. This simply forces the regex parser to gobble-up the rest of the URL-path, which you don't appear to be interested in anyway.
However, this also looks like it might be a bit too general? I assume you don't have any static resources (JS, CSS or images, etc) that have a URL-path that starts /product_? If you do then this pattern should be made more restrictive, otherwise it will end up "testing" many more requests than it needs to.

RewriteCond %{DOCUMENT_ROOT}\/\local_http_cache\/product_%1.php -f

You don't need to backslash escape the slashes or l(?) in the TestString. This isn't a regex, but even if it was these characters carry no special meaning.

/local_http_cache/product_%1.php?CacheFlag [PT,QSA,L]

Do you need the PT flag here (or on any of these directives)? This results in the substitution string being treated as a URL-path and the rewriting process starts over. If you are rewriting directly to a file (which is assumed in a vHost context), which requires no further processing, then the PT flag can be omitted.
In which case I'd also question the use of the CacheFlag query string. You could change this to an environment variable (eg. E=UniqueCacheFlag:1 in the RewriteRule flags) and check for this in the /local_http_cache directory instead (eg. Require env UniqueCacheFlag - assuming Apache 2.4). The QSA flag could also be omitted in this case. This would also make direct access "impossible".

The ?CacheFlag doesn't do anything particularly functional - but a rule in /local_http_cache/'s .htaccess file tells it to forbid anything that doesn't have that flag

Since efficiency is the question here... why are you using .htaccess? Especially since you have the other directives in the vHost. It's not just the fact that there is a .htaccess file - it's that they are enabled to start with (Apache will search for them). The directives in the /local_http_cache/.htaccess file should be moved to an appropriate <Directory> section in the vHost and AllowOverride None should be set for the document root, to disable .htaccess files.

RewriteRule ^/product_([^.]+).*$ /path/to/OurEcommerceSystem?ProductID=$1 [PT,QSA]

Shouldn't you have an L flag here to prevent further processing?
So, in summary, we have:
# product pages
RewriteCond %{DOCUMENT_ROOT}/local_http_cache/product_$1.php -f
RewriteRule ^/product_([^.]+) /local_http_cache/product_$1.php [E=UniqueCacheFlag:1,L]
RewriteRule ^/product_([^.]+) /path/to/OurEcommerceSystem?ProductID=$1 [QSA,L]

The same would then apply to the # category pages block.


text:
Q: Dozer collection field not excluded I'm using Dozer to map my entities to my DTO's
My problem is on an entity with collections lazy loaded. I use a mapping to tell to Dozer to exclude the collections fields to avoid a Lazy Loading exception.
Even with this specific mapping Dozer seems to try to map the collections and then Hibernate throws the Lazy Loading exception...
Here is my specific mapping:
 <mapping map-id="employe_simple">
    <class-a>ch.tupperware.tuppergestion.entity.AbstractEmployeEntity</class-a>
    <class-b>ch.tupperware.tuppergestion.dto.AbstractEmployeDto</class-b>
    <field-exclude>
      listeClients
      listeClients
    </field-exclude>
    <field-exclude>
      reunions
      reunions
    </field-exclude>
    <field-exclude>
      responsable
      responsable
    </field-exclude>
  </mapping>

Here is my entity:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@org.hibernate.annotations.DiscriminatorFormula(value="TYPE_PERSONNE")
@Table(name="EMPLOYE")
public class AbstractEmployeEntity implements UserDetails, Comparable<AbstractEmployeEntity> {

    private static final long serialVersionUID = 3577478107563521474L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "ID_EMPLOYE")
    private Long id;

    @Column(name= "NOM")
    private String nom;

    @Column(name = "PRENOM")
    private String prenom;

    @Column(name = "TYPE_PERSONNE")
    private TypeEmploye typePersonne;

    @OneToMany(fetch = FetchType.LAZY, mappedBy="referent")
    private Set<AbstractClientEntity> listeClients;

    @OneToMany(mappedBy="employe", fetch=FetchType.EAGER)
    @Cascade(CascadeType.PERSIST)
    private Set<RoleEntity> authorities = new HashSet<RoleEntity>();

    @OneToMany(fetch = FetchType.LAZY, mappedBy="employe")
    private Set<ReunionEntity> reunions = new TreeSet<ReunionEntity>();

    @ManyToOne(fetch = FetchType.LAZY)
    private AbstractEmployeEntity responsable;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "DERNIER_LOGIN")
    private Date dernierLogin;

getter and setter....
}

Here is the way I try to do the specific mapping:
mapper.map(empl, AbstractEmployeDto.class, "employe_simple")

In this statement as soon as my employee has the collection reunions not empty, Hibernate throws a Lazy Loading exception...
I want to keep the lazy loading on the collections because I don't need them in the method. That's why I use a specific mapping to not map them.


text:
Q: android, text retrieved from webservices My problem is all the texts comes from webservices. So, at the beginning, I call the webservice and I have to set the texts in strings.xml. I know writing in strings.xml it's impossible but we had the same problem on iOs and a solution has been found here http://iosapplove.com/archive/2013/01/localizable-strings-how-to-load-translations-dynamically-and-use-it-inside-your-iphone-app/.
So my question is : Is there a similar way on android ? (I think no)
It exists alternative way like using database or sharedPreferences but these solutions won't be very effective. Moreover, the application will contain many languages.
So my second question : What is the best way to do this ?

A: As you already know, the strings.xml files will not exist in the APK. This means that there is no way to change what getResources().getString(R.string.mystring) will return.
You say that "it's a request from customer". My suggestion is that you tell the customer "this is a bad idea". Because it really is.
If the customer persists I guess your only option is to download the texts in whatever language it is that you need and store it in your apps external file storage. The suggestion to use a properties file is good. Load it as an InputStream and get strings from it.
Have you considered what will happen if the app is in flight mode or does not have a network available when started? Will you provide default values?
Also, with this solution you will not be able to set any texts in TextViews or similar in XML since the system won't have access to your downloaded translations in the properties files.
If you still go ahead with this I'd also suggest that you wrap the Properties file into some other class and fall back to whatever texts you have in your strings.xml if a text doesn't exist in the properties file or if it wasn't downloaded for some reason:
class TextRetriever {

    // the downloaded texts go here
    private Properties properties;

    private Context context;

    public String getString(String key) {
        String s = properties.getProperty(key);
        // not found in properties file
        if(s == null) {
            // fall back to value in strings.xml
            s = context.getResources().getIdentifier(key, "string", context.getPackageName())
        }
        return s;
    }
}


text:
Q: How to change layout content the same throughout all erb files I am new to using sinatra
I have in my layout erb file a navbar that stays consistent through all my pages using yield
At the same time I have this h1 tag above the nav bar that I want to keep changed throughout all my erb pages
ex:

Home

Home

About Us

Gallary

    <%= yield %>

How do I manipulate that h1 tag to print different strings throughout all my pages? Do I store it in my rb file within a method?

A: Refer here - http://www.sinatrarb.com/contrib/content_for
I think in your view you can
<% content_for :title do %>
  "Your cool page title"
<% end %>

In your layout.erb

<%= yield_content :title %>


text:
Q: Por que trocar itens de uma lista com atribuição múltipla não funciona quando uso o "index()" inline na atribuição? Consigo trocar 'a' e 'b' com este código:
lista = ['a', 'b', 'c']

item = 'a'        # itens que quero localizar e trocar
outro_item = 'b'  #

indice_item       = lista.index(item)       # obtenho a posição de ambos
indice_outro_item = lista.index(outro_item) #

# tento fazer a troca invertendo os índices
lista[indice_item],lista[indice_outro_item]=lista[indice_outro_item],lista[indice_item]

# deu certo
print(lista[0]) # b
print(lista[1]) # a
print(lista[2]) # c

Funcionou: https://ideone.com/2dZvJV

Só que se eu não usar as variáveis intermediárias e chamar index sempre, mas mantendo a lógica original, a troca não acontece:
lista = ['a', 'b', 'c']

item = 'a'
outro_item = 'b'

# aqui estou tentando fazer lista[0,1]=lista[1,0] com indexof diretamente:
lista[lista.index(item)],lista[lista.index(outro_item)]= lista[lista.index(outro_item)],lista[lista.index(item)]

# não trocou!
print(lista[0]) # a
print(lista[1]) # b
print(lista[2]) # c

Qual o motivo do segundo código não funcionar como o primeiro?
https://ideone.com/hs7YOA

A: Segundo a documentação, expressões são avaliadas da esquerda para a direita, e em caso de atribuições, tudo que está à direita do = é avaliado primeiro. Ou seja, em uma expressão como a sua, a ordem de avaliação é:
expr3, expr4 = expr1, expr2

Primeiro ele avalia expr1, depois expr2, depois expr3 (e atribui o valor de expr1)  e depois expr4 (e atribui o valor de expr2).
No seu caso, temos:
lista[lista.index(item)], lista[lista.index(outro_item)] = lista[lista.index(outro_item)], lista[lista.index(item)]

Ou seja, primeiro ele vai avaliar tudo à direita do =. Então primeiro é avaliado lista[lista.index(outro_item)], que resulta em 'b' e depois lista[lista.index(item)], que resulta em 'a'. O resultado dessas 2 expressões resulta na tupla ('b', 'a').
Depois ele avalia a primeira expressão à esquerda do =, que é lista[lista.index(item)]. Ela resulta em lista[0] (já que 'a' está no índice zero), e este recebe o valor 'b'. Ou seja, agora a lista é ['b', 'b', 'c'].
Então, ao avaliar lista[lista.index(outro_item)], o resultado também será lista[0], pois index retorna a primeira posição na qual o elemento sendo procurado está. E a primeira posição onde tem um 'b' agora é zero, por isso lista[0] receberá o valor 'a', e a lista voltará a ser ['a', 'b', 'c'].
Por isso que o primeiro código funciona, porque você só busca os índices uma vez no início, e ao avaliar as expressões durante a atribuição estes índices não mudam. Já ao chamar index toda hora, ele corre o risco de retornar um valor diferente, já que a lista é alterada durante o processo.

Podemos ver isso criando uma subclasse de list, só para visualizar melhor:
class mylist(list):
    def index_dir(self, i):
        x = super().index(i)
        print(f'index_dir({i})={x}')
        return x
    def index_esq(self, i):
        x = super().index(i)
        print(f'index_esq({i})={x}')
        return x
    def __getitem__(self, i):
        x = super().__getitem__(i)
        print(f'get({i})={x}')
        return x
    def __setitem__(self, i, value):
        print(f'set({i})={value}')
        super().__setitem__(i, value)
        print(f'lista agora é: {self}')

lista = mylist(['a', 'b', 'c'])
item = 'a'
outro_item = 'b'
lista[lista.index_esq(item)],lista[lista.index_esq(outro_item)] = lista[lista.index_dir(outro_item)],lista[lista.index_dir(item)]

Criei 2 métodos index para deixar claro qual está sendo chamado à direita e à esquerda do =. A saída é:
index_dir(b)=1
get(1)=b
index_dir(a)=0
get(0)=a
index_esq(a)=0
set(0)=b
lista agora é: ['b', 'b', 'c']
index_esq(b)=0
set(0)=a
lista agora é: ['a', 'b', 'c']

Veja como à direita do = ele encontra corretamente os elementos, mas ao fazer a primeira atribuição, a lista é modificada para ['b', 'b', 'c'], e ao chamar index para encontrar o 'b' ele retorna zero - e por isso é o elemento no índice zero que recebe `'a'.
Agora se eu fizer:
indice_item       = lista.index_dir(item)
indice_outro_item = lista.index_dir(outro_item)
lista[indice_item],lista[indice_outro_item]=lista[indice_outro_item],lista[indice_item]

A saída é:
index_dir(a)=0
index_dir(b)=1
get(1)=b
get(0)=a
set(0)=b
lista agora é: ['b', 'b', 'c']
set(1)=a
lista agora é: ['b', 'a', 'c']

Pois os índices só são buscados uma vez, e durante as atribuições eles permanecem com os mesmos valores, portanto cada posição recebe o valor correto.


text:
Q: Centering a webpage - what am I missing? I don't know what I'm missing. I am simply trying to center the page and nothing I do is working. I have the wrapper with "align-items: center;"... wouldn't that do it? Please help me out. Here is the current code:

#Table_01 {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 850px;
}
#wrapper {
  align-items: center;
}
#themeBG {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 849px;
  height: 333px;
}
#inThisIssue {
  position: absolute;
  left: 0px;
  top: 333px;
  width: 266px;
  height: 65px;
}
#headlineNewDept {
  position: absolute;
  left: 266px;
  top: 333px;
  width: 584px;
  height: 65px;
}
#sidebar {
  position: absolute;
  left: 0px;
  top: 398px;
  width: 266px;
  height: 2148px;
}
#main {
  position: absolute;
  left: 266px;
  top: 398px;
  width: 583px;
  height: 2149px;
  text-align: left;
}

Main content.

A: #Table_01 {
margin:0 auto;
width:850px;
position:relative;
}

Position absolute with left 0 will slam it to the left.  Try the above.


text:
Q: react-fine-uploader S3 upload using dynamic filename Background
I am integrating creating a react app using react-fine-uploader to upload directly to an S3 bucket, I don't have any server-side code.  I've been able to upload to my bucket using the regular uuid that react-fine-uploader creates out of the box.  What I'd now like to do is dynamically create the file name so that I can write the files to s3 "folders".
Problem
I know I can configure my uploader.options.objectProperties.key, and pass it a function such as:
var uploader = new qq.s3.FineUploader({
    // ...
    objectProperties: {
        key: function(fileId) {
            return 'folder/within/bucket/' + this.getUuid(fileId);
        }
    }
});

(Taken from another answer)
This is fine when you want to handle values that you can get from the file/uploader (such as the uuid), and with other static info.  What I want is to include a folder name that has been passed to this component from elsewhere.  Here's my attempt so far:
//imports...
const uploader = new FineUploaderS3({
    options: {
        //other options...
        objectProperties: {
            key: function(fileId) {
                return folderName + '/' + this.getUuid(fileId);
            }
        }
    }
});

var folderName = null;

class FileUpload extends Component {
    constructor(props) {
        super(props);

        folderName = this.props.folderName;
    }

    render() {

        return (

                <Gallery uploader={uploader} />

        );
    }
};

export default FileUpload;

Currently this adds this into a folder in s3 called "null", but I am successfully passing this component the folderName in props.
What do I need to do to connect these things up?

A: What's the value of the fileUpload prop when FileUpload is initially rendered? As written, this will only set the fileUpload variable in the scope the FineUploaderS3 instance has access to when the component is initially rendered. If the fileUpload prop is given a value later, you may need to use componentWillReceiveProps() to update folderName when that happens (and you can only have one FileUpload component, as the last one to render will win).

Another approach is to create objects which depend on a component's props or state as part of its lifecycle and store them on the component instance itself, e.g.:
class FileUploadComponent extends Component {
  constructor(props) {
    super(props)
    // We can't use an arrow function for the key function below as we need to
    // access both this component's props and the FileUploader instance within it
    let component = this
    this.uploader = new qq.s3.FineUploader({
      // ...
      objectProperties: {
        key(fileId) {
          return `${component.props.folderName}/${this.getUuid(fileId)}`
        }
      }
    })
  }

  render() {
    return

      <Gallery uploader={this.uploader}/>

  }
}


text:
Q: Only Push onto array once versus pushing to array every time condition is met I am importing excel files that contain customer orders like so
onFileChange(event: any) {
    const inputFile: DataTransfer = <DataTransfer>(event.target);
    const fileReader: FileReader = new FileReader();
    fileReader.onload = (event: any) => {
      const binaryString: string = event.target.result;
      const workBook: XLSX.WorkBook = XLSX.read(binaryString, { type: 'binary', sheetStubs: true});
      /* sheetstubs true supposedly shows empty cells but isn't */
      console.log(typeof binaryString)

      const workSheetName: string = workBook.SheetNames[0];
      console.log(workSheetName)
      const workSheet: XLSX.WorkSheet = workBook.Sheets[workSheetName];

      this.data = <Array>(XLSX.utils.sheet_to_json(workSheet, { header: 1, blankrows: true }));

    };
    fileReader.readAsBinaryString(inputFile.files[0]);
    console.log(this.data)
  }

The way the excel files are imported an object of arrays where each array is a row of the excel sheet.
In the following code snippet, I am searching for items in a column to identify the column in an excel sheet that has the shoe brands requested by a customer in the code
for (var i=0; i<this.data.length; i++){
      if (this.data[i].indexOf('Adidas') != -1) {
        var manIndex = this.data[i].indexOf('Adidas')
        for( var j = 0; j<this.data.length; j++){
          this.manufactArray.push(this.data[j][manIndex])
        }

      }
      else if (this.data[i].indexOf('Puma') != -1) {
        var manIndex = this.data[i].indexOf('Puma')
        for (var j=0; j<this.data.length; j++) {
          this.manufactArray.push(this.data[j][manIndex])
        }
      }
      else if (this.data[i].indexOf('Nike') != -1) {
        var manIndex = this.data[i].indexOf('Nike')
        for(var j = 0; j<this.data.length; j++){
          this.manufactArray.push(this.data[j][manIndex])
        }
      }
      }

    }

this works in that it pushes all of the items in the relevant column into the array but it does so every time the conditions are met and as such the same column is pushed into the array a bunch of times as opposed to only pushing the column items once. Is there a way maybe using the % or other function so that the column is only pushed into the array one time? So if I had a customer sheet come in like this:

I would want the array to have [Nike, Adidas, Puma, Puma, Asics, Nike]

A: One way is to use a Set. You probably don't want to check if it is in the array before you add it, because then you may have O(n²) time complexity, which can be undesirable.
You can add it to a set, and return as a set, or if needed, return as an array:

const mySet = new Set();

mySet.add(123);
console.log([...mySet]);

mySet.add("hello world");
console.log([...mySet]);

mySet.add(123);
console.log([...mySet]);

I would have just used console.log(mySet) but for some reason StackOverflow can't print out its value (unlike Node.js or Chrome). But then it shows how to convert the set back to an array.  You can also use Array.from(mySet).
So in your code, you probably have:
this.manufactSet = new Set();

and in the loop:
this.manufactSet.add(this.data[j][manIndex]);

and after the loop, you can set it back to an array:
this.manufactArray = [...this.manufactSet];

But I don't quite get your code:
for (var i=0; i<this.data.length; i++){
      if (this.data[i].indexOf('Adidas') != -1) {
        var manIndex = this.data[i].indexOf('Adidas')
        for( var j = 0; j<this.data.length; j++){
          this.manufactArray.push(this.data[j][manIndex])
        }

Why when you found Adidas, then you push everything into the result?
Shouldn't you do:
for (var i=0; i<this.data.length; i++){
      if (this.data[i].indexOf('Adidas') != -1) {
        var manIndex = this.data[i].indexOf('Adidas')
        this.manufactArray.push(this.data[i][manIndex])

?
Is this.data[i] a string that might have  "Cool Adidas NMD hard to find"... and once you find the "location" of Adidas, why do you just push that character into the result?
Don't you want to push the whole string into the result?
for (var i=0; i<this.data.length; i++){
      if (this.data[i].indexOf('Adidas') != -1) {
        var manIndex = this.data[i].indexOf('Adidas')
        this.manufactArray.push(this.data[i])

So after checking what data[i] is and what you would like to do, seems like this is what you want to do:
Note that you mentioned you actually want the manufacturer to appear more than once, like ["Adidas", "Adidas", "Nike", "Puma", "Nike"], so I won't use a set as the result below:
const someManufacturers = new Set(['Adidas', 'Puma', 'Nike']);

function getColumnNumber() {
  for (var i = 0; i < this.data.length; i++) {
    for (var j = 0; j < this.data[i].length; j++) {
      if (someManufacturers.has(this.data[i][j])) return j;
    }
  }
}
var manufacturerColumnNumber = getColumnNumber();

for (var i = 0; i < this.data.length; i++) {
  this.manufactArray.push(this.data[i][manufacturerColumnNumber]);
}

Actually, there is a better way to write it now in ES6:
const someManufacturers = new Set(['Adidas', 'Puma', 'Nike']);

function getColumnNumber() {
  for (const row of this.data) {
    for (let i = 0; i < row.length; i++) {
      if (someManufacturers.has(row[i])) return i;
    }
  }
}
var manufacturerColumnNumber = getColumnNumber();

for (const row of this.data) {
  this.manufactArray.push(row[manufacturerColumnNumber]);
}

I think I see what you mean by "pushing" every time instead of once. You mean if you see Adidas, you push the whole column values to the array, and the next row, you see Nike, and you push the whole column values to the array again. You could have just returned if you put that in a function. So once you see Adidas, then just push all values in that column to the array and return from the function.


text:
Q: WooCommerce add_to_cart Shortcode - Product already in Cart I've added the WooCommerce shortcode "add_to_cart" successfully on a custom post type page.
[add_to_cart id="510"]
If there is nothing in the cart, it redirects to the shopping cart adding the product as intended. However, if the product is already in the cart and the user click the button on the custom post type page, it redirects back to itself.
The user can't add more than one of a given item to the cart. How can I check to see what's in the cart, so that if the user clicks the button it will redirect to the shopping cart if that product is already in there? Don't need any error message to come up like on the standard WooCommerce product page.
Thanks in advance for any ideas!
Aaron

A: Try this,
When the users clicks on the button you can check the current cart item with this code.
global $woocommerce;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {

  if($cart_item['product_id'] == $your_product_id){
   //the item already added to the cart
 }
}

This will iterate the all items in the cart also if you want to add a product forcefully to the cart just need this,
$woocommerce->cart->add_to_cart($product_id,$qty);

Hope its helps..

A: I was looking for a way to add a cart button to the bottom of my product pages. In the end I added the following html code:
<form class="cart" method="post" enctype='multipart/form-data'>
    <button type="submit" name="add-to-cart" value="820" class="single_add_to_cart_button button alt">Add to basket</button>
</form>

The value is the product ID.
Hope this helps someone with the same issue


text:
Q: How would I hide the new Windows 11 volume modal? Just received an update on Windows 11 (22612, but I'm not sure if that's the one that introduced the change) that changes the volume and brightness popups to now appear in the bottom center of the screen. I use ModernFlyouts and having the two popups on the screen at once is annoying, so I'm wonder if there is a way to hide the default Windows one completely.
Thanks.


text:
Q: Jquery JTable Load from 2 Tables I am using Jquery-JTable in my website to load details in a grid view and to let user be able to modify, delete app accordingly.
I am loading data successfully from 2 tables and then display them in my div. Now the user would like to modify a record accordingly to his/her wish.
I would like to let the user choose from a dropdown list obtained from another table. Can this be done?
Code Below: As you can see I am loading data from multiple tables using InnerJoin. For example I would like to let the user choose another Category or Language etc.
$queryString = "SELECT `app_id`,`app_name`,`app_type`,`app_url`,`AppAccepted`,`BenefitApp`, application_ageGroup.ageGroup,application_category.category, application_Country.country,application_Language.language FROM application INNER JOIN application_ageGroup ON application.ageGroup_id = application_ageGroup.ageGroup_id INNER JOIN application_category ON application.Category = application_category.category_id INNER JOIN application_Country ON application.country_id = application_Country.country_id INNER JOIN application_Language ON application.language_id = application_Language.language_id ORDER BY $jtSorting LIMIT $jtStartIndex,$jtPageSize";

Regards,

A: Make the Category column as dropdown and bind it with your query dataset :
$('#Table').jtable({
        paging: true,
        pageSize: 200,
        sorting: true,
        defaultSorting: 'Category ASC',
        selecting: false,
        multiselect: false,
        selectingCheckboxes: false,
        actions: {
            listAction: '/Application/GetData',
            updateAction: '/Application/EditData'
        },
        fields: {
            Category: {
                title: 'Category',
                width: '10%',
                list: false,
                sorting: true,
                options: '/Application/GetCategories'
            }
        });

In your controller action, fetch Category lists:
    [HttpPost]
    public JsonResult GetCategories()
    {
        try
        {
            DataTable dtCategories = new DataTable();

            string query = "SELECT .....";

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                connection.Open();
                dtCategories.Load(command.ExecuteReader());
            }

            List<Store> categoryList = DatatableToGenericList(dtCategories);

            var categories = categoryList.Select(category => new { DisplayText = category.Name , Value = category.Id }).OrderBy(s => s.DisplayText);

            return Json(new { Result = "OK", Options = categories });
        }
        catch (Exception ex)
        {
            return Json(new { Result = "ERROR", Message = ex.Message });
        }
    }

private static List<Store> DatatableToGenericList(DataTable table)
    {
        var categoryList = new List<Category>(table.Rows.Count);
        foreach (DataRow row in table.Rows)
        {
            var values = row.ItemArray;
            var store = new Category()
            {
                Id = values[0].ToString(),
                Name = values[1].ToString()
            };
            categoryList.Add(store);
        }

        return categoryList;
    }

Category Model
public class Category
{
    public string Id { get; set; }

    [Required]
    public string Name { get; set; }
}

Hope this helps..


text:
Q: header Element prevent execution of Javascript sorry for my English...
I to try an image zoom as here to say, it working (the image zoom) without  Tag.

Width the  tag

When getting with the Maus on the image, the image disappears.

Here I can show how to build my Html code.

$('.wrapper').on('mouseenter', function() {
  $('.img').css({
    transform: 'scale(2.5)'
  });
});

$('.wrapper').on('mouseleave', function() {
  $('.img').css({
    transform: 'scale(1.0)',
    backgroundPosition: 'center center'
  });
});

$('.wrapper').on('mousemove', function(e) {
  $('.img').css({
    backgroundPosition: (e.pageX * -1) + 'px ' + (e.pageY * -1) + 'px'
  });
});
.row {
  margin: 10px;
}

.wrapper {
  width: 300px;
  height: 300px;
  border: 1px solid navy;
  overflow: hidden;
}

.img {
  width: 100%;
  padding-bottom: 100%;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

        Home

        Taschen & Rucksäcke

          Taschen, Tablettaschen & Computertaschen
          Rucksäcke
          Beutel
          Gürteltasche, Mäppchen & Schnupftabakdose

        Haus

          Dekoration
          Teppich
          Yogamatten & Necessaire

        Kleidung

          T-Shirts für Frauen & Männer
          Hösen für Frauen & Männer
          Schals, Mützen & Hute
          Sandalen

        Schmuck

          Ringe, Ohrringe, Ketten ...

        Über uns

          Über uns
          Kundenservice

        🌍 English

          Spanisch

I too tried with and without  Element, and to show which only working without  Element....
Can please someone help me and say where is my mistake? , Thanks!

A: Your code works, fine, if you had give your wrapper bigger size you would have seen your img does not lose it self but moves up behind header.
Problem  was  here in your js:  backgroundPosition: (e.pageX * -1) + 'px ' + (e.pageY * -1) + 'px'
This positioned your zoomed image behind header. If you remove it shows in box and zooms but does not update zoom on mouse movement.
I tired to play around with this but I couldn't make it work and I don't have any time for this anymore. So i am leaving this answer here maybe someone else has an idea.
I tried to play around with this:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX
I could make mouse to react only for inside wrapper but I couldn't make the picture work to react to this.
Good luck.

$('.wrapper').on('mouseenter', function() {
  $('.img').css({
    transform: 'scale(1.5)'
  });
});

$('.wrapper').on('mouseleave', function() {
  $('.img').css({
    transform: 'scale(1.0)',
    backgroundPosition: 'center center'
  });
});

$('.wrapper').on('mousemove', function(updateDisplay) {
var box = document.querySelector(".wrapper");
var pageX = document.getElementById("x");
var pageY = document.getElementById("y");
function updateDisplay(event) {
    $('.img').css({
 backgroundPosition: (event.pageX * -1) + 'px ' + (event.pageY * -1) + 'px'
  });
}
box.addEventListener("mousemove", updateDisplay, false);
box.addEventListener("mouseenter", updateDisplay, false);
box.addEventListener("mouseleave", updateDisplay, false);
});
.wrapper {
    width: 300px;
    height: 300px;
    border: 1px solid navy;
    overflow: hidden;

}

.img {
     margin-right: auto; /* 1 */
  margin-left:  auto;
    width: 100%;
    padding-bottom: 100%;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}

        Home

        Taschen & Rucksäcke

          Taschen, Tablettaschen & Computertaschen
          Rucksäcke
          Beutel
          Gürteltasche, Mäppchen & Schnupftabakdose

        Haus

          Dekoration
          Teppich
          Yogamatten & Necessaire

        Kleidung

          T-Shirts für Frauen & Männer
          Hösen für Frauen & Männer
          Schals, Mützen & Hute
          Sandalen

        Schmuck

          Ringe, Ohrringe, Ketten ...

        Über uns

          Über uns
          Kundenservice

        🌍 English

          Spanisch


text:
Q: persisting data in mvc I am beginning to use ASP.NET MVC and i have a navigation which is build with javascript and css. The Navigation is collapsable, so that the menu only takes like 1cm when its collapsed.
My problem is that i need to change the state (collapsed/expanded) by clicking on a button and setting a css class on the menu.
But when i click on a menu-entry the page gets reloaded  and so the css-class gets lost too.
How can i persist such data correctly? In normal views i could pass it to my viewmodel, but how can i do this in my _layout.cshtml? (i cant set a model there, right?)
What i tried was using the jquery plugin "cookies" but it only works sometimes (i think the problem is somewhere within the options of the plugin - maybe i have to set a domain or something...). Furthermore it would be nice if the solution wouldnt require the user to allow cookies.
Im glad for any help!
edit:
ok, what i tried now is:
//the view
@model NHibernateSimpleDemoMVC.Models.MenuModel
....
<a id="togglemenu" />

@Html.HiddenFor(x => x.IsCollapsed, new { @id = "collapsedHdn" })

...

<script>
jQuery('#togglemenu').click(
    function () {
        if (jQuery("#collapsedHdn").val() == "true") {
            jQuery("#collapsedHdn").val("false")
        } else {
            jQuery("#collapsedHdn").val("true")
        }
    });

jQuery('#nav > li').click(
    function () {
        var name = jQuery(this).attr("id");
        jQuery("#selectedHdn").val(name);
    }
    );

jQuery(document).ready(function () {
    //set selected node
    if (jQuery("#collapsedHdn").val() == "true") {
       ... collapse ...
    }
     if (jQuery("#selectedHdn").val() != "") { //this is always empty ("")
        var name = "#" + jQuery("#selectedHdn").val();
        jQuery(name).addClass("current");
    }
});

</script>

//the model
public class MenuModel
{
    public bool IsCollapsed { get; set; }
    public string SelectedEntry { get; set; }

    public MenuModel(){
        IsCollapsed = false;
        SelectedEntry = "";
    }
}

... my hidden fields seem to not keep their value after the postback...

A: There's a useful related question: ASP.NET MVC Razor pass model to layout

A: There's usually a correlation between a value on the page and the navigation menu item pointing to that page. E.g a Title or something like that.
If there is, then you can use jQuery/Javascript to set the css class once the DOM is fully loaded by reading this value and finding the corresponding menu item.
This is definitely not something you would use cookies for.


text:
Q: Multithreading with SQLite and Objective-C I have a couple of threads and I'm using SQLite for storage. When I'm trying to access the database I'm getting SQLITE_BUSY error.
Is there a way how to fix this problem other than trying at each request ?

A: You are most likely running in serialized mode. But ... you're probably looking to run in multi-threaded mode instead. Note that you will need a separate database connection in each thread if you go that route.
Here is the link to the documentation goodness: http://www.sqlite.org/threadsafe.html

A: Ignore my last answer.
You can use the sqlite3_errmsg function to get the error message as string and print it using NSLog or other ways as soon as error occurs to find the more appropriate and proper reason.
http://www.sqlite.org/c3ref/errcode.html
You probably seem to be running in to serialization issue; I am not sure where.


text:
Q: Get memory and Data consumed by individual Application through code in android Is there any way to get the mobile data and the memory consumed by an app through code. As like it show on the App setting page, I need to show the details within the app. Kindly suggest
App Settings screen

A: you can do it using Profiler but you cant get it programatically

https://developer.android.com/studio/profile/android-profiler
details about each of the profilers, see the following:
Inspect CPU activity and traces with CPU Profiler Inspect the Java
  heap and memory allocations with Memory Profiler Inspect network
  traffic with Network Profiler Inspect energy usage with Energy
  Profiler

A: For Data usage you can try this below code it will return the number of bytes received across mobile networks since device boot:
Toast.makeText(this, android.net.TrafficStats.getMobileRxBytes()+"Bytes", Toast.LENGTH_SHORT).show();

*

*https://developer.android.com/reference/android/net/TrafficStats.html
For memory consuption you can refer this duplicate question:

*

*How to get current memory usage in android?


text:
Q: keras mask not propagated Keras (tensorflow 2.6 backend) masks supposed to propagate through the network, as mentioned in the docs:

When using the Functional API or the Sequential API, a mask generated by an Embedding or Masking layer will be propagated through the network for any layer that is capable of using them.

Both Conv1D and GlobalMaxPool1D support masks but mask is not propagated, as demonstrated by the following example,

*

*model1 applies mask and GlobalMaxPool1D

*model2 applies mask and Conv1D

*model3 applies mask and Conv1D followed by GlobalMaxPool1D
from tensorflow.keras import layers
from tensorflow.keras import models
from tensorflow.keras import initializers
import numpy as np

mask_val = 10.
inp = layers.Input(shape = (4,3))
masked = layers.Masking(mask_value = mask_val)(inp)
max_pool = layers.GlobalMaxPool1D()(masked)
model1 = keras.models.Model(inputs = inp, outputs = max_pool)
#--- initialize the conv kernel to -1. so it's easy to interpret output
conv = layers.Conv1D(1, 2, padding = 'valid', kernel_initializer = initializers.Constant(-1.))(masked)
model2 = keras.models.Model(inputs = inp, outputs = conv)
out = layers.GlobalMaxPool1D()(conv)
model3 = models.Model(inputs = inp, outputs = out)

Now test these 3 models on a simple input, 2 samples of dimension 3, followed by 2 masked samples:
x0 = np.concatenate((np.ones((1,2,3)), mask_val * np.ones((1,2,3))), axis = 1)
model1(x0) # outputs [1,1,1], as expected
model2(x0) # outputs [-6, -3, 0] as expected
model3(x0) # outputs [0], but should output [-3] as the 0 value should be masked

Am I missing something?

A: So, I was wrong thinking that Conv1D and GlobalMaxPool1D support masks. Turns out that:
layers.GlobalMaxPooling1D().supports_masking #--- this property is False
layers.Conv1D(1,1).supports_masking          #--- this property is False

It seemed to support mask since the masking layer replaces the masked values by 0s, and then the outputs of both the Conv1D layer and the GlobalMaxPooling1D layer were not affected by these 0.
A different input (with -1 instead of 1 as the un-masked values) shows it:
x0 = np.concatenate((-np.ones((1,2,3)), mask_val * np.ones((1,2,3))), axis = 1)
l_masked = layers.Masking(mask_value = mask_val)
l_max_pool =  layers.GlobalMaxPool1D()
l_max_pool(l_masked(x0)) #--- returns [0,0,0] - ignoring the mask :(


text:
Q: What does this function ft_isalnum do? I am reading a program which contains the following function, which is
int ft_isalnum(int c)
{
    return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
            || (c >= '0' && c <= '9'));
}

I don't quite understand what does this function intend to do?

A: As suggested by its name, the function checks if the given character is alphanumeric.
Assuming ASCII character encoding where A-Z and a-z are stored consecutively, it checks if the character is in either the 'A' to 'Z' range, the 'a' to 'z' range, or the '0' to '9' range and returns true if any of those conditions are satisfied.

A: Write a program to figure it out:
#include <stdio.h>
#include <ctype.h>

int ft_isalnum(int c)
{
    return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'));
}

int main(void)
{
    for (int i = 0; i < 128; putchar(++i % 8 ? ' ' : '\n'))
        printf("%3d '%c' %c ", i, isprint((char unsigned)i) ? i : '?', ft_isalnum(i) ? 'X' : ' ');
    putchar('\n');
}

Output

  0 '?'      1 '?'      2 '?'      3 '?'      4 '?'      5 '?'      6 '?'      7 '?'
  8 '?'      9 '?'     10 '?'     11 '?'     12 '?'     13 '?'     14 '?'     15 '?'
 16 '?'     17 '?'     18 '?'     19 '?'     20 '?'     21 '?'     22 '?'     23 '?'
 24 '?'     25 '?'     26 '?'     27 '?'     28 '?'     29 '?'     30 '?'     31 '?'
 32 ' '     33 '!'     34 '"'     35 '#'     36 '$'     37 '%'     38 '&'     39 '''
 40 '('     41 ')'     42 '*'     43 '+'     44 ','     45 '-'     46 '.'     47 '/'
 48 '0' X   49 '1' X   50 '2' X   51 '3' X   52 '4' X   53 '5' X   54 '6' X   55 '7' X
 56 '8' X   57 '9' X   58 ':'     59 ';'     60 ''     63 '?'
 64 '@'     65 'A' X   66 'B' X   67 'C' X   68 'D' X   69 'E' X   70 'F' X   71 'G' X
 72 'H' X   73 'I' X   74 'J' X   75 'K' X   76 'L' X   77 'M' X   78 'N' X   79 'O' X
 80 'P' X   81 'Q' X   82 'R' X   83 'S' X   84 'T' X   85 'U' X   86 'V' X   87 'W' X
 88 'X' X   89 'Y' X   90 'Z' X   91 '['     92 '\'     93 ']'     94 '^'     95 '_'
 96 '`'     97 'a' X   98 'b' X   99 'c' X  100 'd' X  101 'e' X  102 'f' X  103 'g' X
104 'h' X  105 'i' X  106 'j' X  107 'k' X  108 'l' X  109 'm' X  110 'n' X  111 'o' X
112 'p' X  113 'q' X  114 'r' X  115 's' X  116 't' X  117 'u' X  118 'v' X  119 'w' X
120 'x' X  121 'y' X  122 'z' X  123 '{'    124 '|'    125 '}'    126 '~'    127 '?'

The output indicates, on my machine, that characters 0 to 9 and letters A to Z and a to z return a 1 while everything else returns a 0.
Note
Not all characters are printable.
Thanks
To @Swordfish for making the output more attractive and readable.


text:
Q: A accessToken is not valid for connecting to Azure DevOps deployment group from Windows server In Azure Devops Server, I have created a group in  Deployment Groups. A registration script was created for run in the target server. This is the generated script.

$ErrorActionPreference="Stop";If(-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() ).IsInRole( [Security.Principal.WindowsBuiltInRole] "Administrator")){ throw "Run command in an administrator PowerShell prompt"};If($PSVersionTable.PSVersion -lt (New-Object System.Version("3.0"))){ throw "The minimum version of Windows PowerShell that is required by the script (3.0) does not match the currently running version of Windows PowerShell." };If(-NOT (Test-Path $env:SystemDrive'azagent')){mkdir $env:SystemDrive'azagent'}; cd $env:SystemDrive'azagent'; for($i=1; $i -lt 100; $i++){$destFolder="A"+$i.ToString();if(-NOT (Test-Path ($destFolder))){mkdir $destFolder;cd $destFolder;break;}}; $agentZip="$PWD\agent.zip";$DefaultProxy=[System.Net.WebRequest]::DefaultWebProxy;$securityProtocol=@();$securityProtocol+=[Net.ServicePointManager]::SecurityProtocol;$securityProtocol+=[Net.SecurityProtocolType]::Tls12;[Net.ServicePointManager]::SecurityProtocol=$securityProtocol;$WebClient=New-Object Net.WebClient; $Uri='https://go.microsoft.com/fwlink/?linkid=2066756';if($DefaultProxy -and (-not $DefaultProxy.IsBypassed($Uri))){$WebClient.Proxy= New-Object Net.WebProxy($DefaultProxy.GetProxy($Uri).OriginalString, $True);}; $WebClient.DownloadFile($Uri, $agentZip);Add-Type -AssemblyName System.IO.Compression.FileSystem;[System.IO.Compression.ZipFile]::ExtractToDirectory( $agentZip, "$PWD");.\config.cmd --deploymentgroup --deploymentgroupname "DG-Test" --agent $env:COMPUTERNAME --runasservice --work '_work' --url 'https://devops.MyCompany.com/tfs/' --collectionname 'Col-FRN-Main' --projectname 'T-MyCompany'; Remove-Item $agentZip;

I run the script then PowerShell asks me to Enter authentication type (press enter for PAT), so I enter an accessToken that is generated in Personal Access Token but PowerShell returns Enter authentication type (press enter for PAT).
I could use the accessToken for connecting Team explorer in Visual studio to my DevOps server and connecting agent pool to my DevOps server, but I have trouble connecting deployment agnet.
What's wrong?

A: When PowerShell asks you to Enter authentication type (press enter for PAT), you are supposed to press enter on your keyboard. Then it will prompt you to enter your Personal Access Token. Follow the prompts and you should be able to connect successfully.


text:
Q: Create a function mapping a number in (0,1) to a color between blue and red I want to create a function colfunc that receives as argument a number between 0 and 1 and returns a color between blue and red, where blue would correspond to a 0 and red to a 1. The ultimate goal is to do something like the following
from matplotlib import pyplot as plt
a=[1,2,3]
plt.plot(a,color=colfunc(0))

and it should plot a blue line
or alternatively if I do
plt.plot(a,color=colfunc(1))

it should return a red line. This is straightforward, but then I also want to be able to do, for example,
plt.plot(a,color=colfunc(0.1))

and it should return a line of the color of a tonality of purple that is closer to blue than to red and so on.

A: What you want to do is called Linear interpolation (sometimes abbreviated to "LERP"). In this case the interpolation is between to two colors in the RGB colorspace.
Here's how to use the pseudocolor() function in one answer of mine to the question Range values to pseudocolor to do what it sounds like you want. (I've renamed it colfunc() as per your question.)
def colfunc(val, minval, maxval, startcolor, stopcolor):
    """ Convert value in the range minval...maxval to a color in the range
        startcolor to stopcolor. The colors passed and the one returned are
        composed of a sequence of N component values (e.g. RGB).
    """
    f = float(val-minval) / (maxval-minval)
    return tuple(f*(b-a)+a for (a, b) in zip(startcolor, stopcolor))

if __name__ == '__main__':
    RED, YELLOW, GREEN  = (1, 0, 0), (1, 1, 0), (0, 1, 0)
    CYAN, BLUE, MAGENTA = (0, 1, 1), (0, 0, 1), (1, 0, 1)
    steps = 10
    minval, maxval = 0.0, 1.0
    incr = (maxval-minval)/steps

    print('val       R      G      B')
    for i in range(steps+1):
        val = minval + round(i*incr, 1)
        print('{:.1f} -> ({:.3f}, {:.3f}, {:.3f})'.format(
                    val, *colfunc(val, minval, maxval, BLUE, RED)))

Output:
val       R      G      B
0.0 -> (0.000, 0.000, 1.000)
0.1 -> (0.100, 0.000, 0.900)
0.2 -> (0.200, 0.000, 0.800)
0.3 -> (0.300, 0.000, 0.700)
0.4 -> (0.400, 0.000, 0.600)
0.5 -> (0.500, 0.000, 0.500)
0.6 -> (0.600, 0.000, 0.400)
0.7 -> (0.700, 0.000, 0.300)
0.8 -> (0.800, 0.000, 0.200)
0.9 -> (0.900, 0.000, 0.100)
1.0 -> (1.000, 0.000, 0.000)

Here's a visualization showing the range of colors it will produce for different values within the minimum and maximum limits inclusively (such as 0.0–1.0):


text:
Q: Asrock J4205 / Intel Apollo Lake will not install Ubuntu 16 / 17 (ASM1061 SATA optical DVD drive cd issue) I have just purchased an AsR J4205 board, hoping to use it as a basic server / NAS - I had an older atom board doing this before, and although not an an expert systems admin am not a newbie either (used / installed Linux since ~ 1998), and have done some googling before posting, and read similar posts on here, Asrock and Debian forums.
So board is sold as Ubuntu 16.10 friendly, I've tried this and 16.04, 17.04 and the daily build, and the install always fails just after the grub screen, usually with
mce: [Hardware Error]: Machine check : 0 Bank 4 a6000000000
sometimes also various other errors, eg : udevadm : relink 'libkmod.so.2 .....
I don't think this is just a UEFI issue, I've tried all options with the CSM mode, and both CD / DVD and USB installers
Similarly the board will install win 10, and boot (gentoo based)  current Sysrescue cd, so hardware is probably OK
I have updated the supplied bios (1.1 reported as buggy) to current 1.4
SO

*

*If anyone has this board working stably what did you do?

*I'm in single channel memory mode (checks ok with memtest) with one 8 gb Sodimm - would dual channel be any better?

*is board just too new / rare to be well supported?

*Could it be worth downgrading BIOS to 1.2 which is the version others have reported as working?

*any other ideas?

Can post further info, diagnostics if that might help.
Thanks

A: A partial answer, which might give others enough info to get their system working, or to give a fuller one if they have in depth knowledge of relevant hardware / linux boot process.
Worked out that next step in boot process might be initialisation of DVD drive, which I had connected to the ASM1061 sata socket (see note above)
Unfortunately the ASM1061 is allergic to (some?) optical drives - not sure if this is plain unsupported, bugs, incompatabilites or what.  Apparently some board / card blurbs warn about this in the small print. Mine didn't!
As above it didn't stop Win10 DVD booting, or sysrescue cd. BUT IT DOES CRASH BOOT OF UBUNTU SETUP, EVEN IF DRIVE IS JUST THERE, AND BOOT IS FROM A PERFECTLY OK USB STICK which is what foxed me for a while.
So easiest fix on this board is to swap sata cables about and connect DVD to SOC based controller, or not use it at all. There may be other options based on controller mode settings, or kernel parameters.
So now it boots and installs happily, just have to return my new hard drive because it has bad sectors and fails SMART :(  So can't comment on long term stability yet.
Further info in these threads:
Can I prevent an IDENTIFY PACKET DEVICE command to a specific device at boot?
Boot failure: failed: command IDENTIFY PACKET DEVICE

A: The most probable cause of this is faulty motherboard unit. I've had similar problems with system stability. All the upgrades of BIOS versions and newest kernel didn't help. I received new unit and it turned out to be motherboard issue. The new board was working perfectly fine.
Related posts
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1682999
Intel Apollo Lake (J3455) random frequent freezes on UI and MCE error on boot

A: I had the same problem with a very strange solution, worked for both Ubuntu 18.04 & Mint 19.2 : the quoted message appears more than once.
After the first time, I took the USB stick out, and then there was some sort of a message complaining about no media, so I stuck it back in. Then the installer started fine.
But I can't assure that it works till the end, since I installed it otherwise in the end: I installed the OS on another computer and transferred the medium to this one. Then I booted Ubuntu and started bootrepair.
After that, the issue was solved.


text:
Q: Module 'Fabric' has no member named 'with' I installed Fabric framework via cocoapods. My project can detect Fabric header and import statement doesn't give any error. But calling
Fabric.with([Crashlytics.self])

gives error

Module 'Fabric' has no member named 'with'

I checked similar problems in with custom framework and in alamofire, but those didn't help.
Update:
I tried running in dummy application and using the pod in it and it worked fine. Seems only to happen in current project, but can't find a reason for it.

A: I resolved it.
Apparently, another pod 'AWSS3' inserted Fabric.h in their own framework in their latest release. Had to downgrade their pod to previous version to make it run.
Reported here. I will update if I get a solution.

A: Solution:
Add import Firebase to the same file where you use Fabric.


text:
Q: $AB=AC$, $BD$ is the angle bisector of $\angle B$ , find $\angle A$ Let $ABC$ be an triangle, $AB=AC$. $BD$ is the angle bisector of $\angle B$, $BD$ intersect $AC$ at point $D$, and $AD=BC+BD$.
show that: $\measuredangle BAC=20^\circ$

Well, If $\measuredangle BAC=20^\circ$, I can prove that  $AD=BC+BD$.
But, if $AD=BC+BD$, How to show $\measuredangle BAC=20^\circ$?
Thanks a lot

A: Let $F$ be the point such that $DF||BC$.
Clearly $BCDF$ is cyclic and since $BD$ is the angular bisector of $\angle CBF$, this implies $CD=DF$.
Let $E$ be the point on $BC$ such that $CE=DE$.
Note that triangles $ECD$ and $AFD$ are similar and since $CD=DF$, they are congruent.
Hence $CE=AD$ and the condition implies $BC+BD=AD=CE=BC+BE$ i.e. $BD=BE$.
So triangle $BDE$ is isosceles and we can now finish this problem off with some angle chasing.
Denote $\angle BAC=4\alpha$.
Then we have $$90^\circ-2\alpha=\measuredangle EDC=\measuredangle EDB+\measuredangle BDC$$$$=\measuredangle BED+180^\circ-\measuredangle DCB-\measuredangle CBD$$$$=4\alpha+180^\circ-(90^\circ-2\alpha)-(45^\circ-\alpha)=45^\circ+7\alpha$$Thus $\alpha=5^\circ$ and hence
$\measuredangle BAC=4\alpha=20^\circ$.

A: By Stewart's theorem we have:
$$ BD^2 = \frac{ab}{(a+b)^2}\left((a+b)^2-c^2\right)=\frac{a^2 b}{(a+b)^2}(a+2b) $$
and by the bisector theorem we have $AD=\frac{b^2}{a+b}$, so $BD^2=(AD-a)^2$ leads to:
$$ a^2 b(a+2b)= (a^2+ab-b^2)^2 $$
so by assuming $b=1$, $a=2\sin\frac{\widehat{BAC}}{2}$ is a root of:
$$ p(x) = x^4+x^3-3x^2-2x+1 = (x+1)(x^3-3x+1). $$
In order to prove $\widehat{BAC}=20^\circ$, we just need to prove that $\sin\frac{\pi}{18}=\cos\frac{4\pi}{9}$ is a root of:
$$ q(x) = 8x^3-6x+1 = 2\cdot T_3(x)+1, $$
that is trivial by using Chebyshev polynomials of the first kind.


text:
Q: How to find such $f(n)$, that satisfies $f(n) \equiv x_n \pmod{ 12}$, where $x_n$ is 12-periodic sequence? How to find such $f(n) \in \mathbb{N}, n \in \mathbb{N}$, that satisfies $f(n) \equiv g(n) \pmod{ 12}, g(n) \in \mathbb{N}$, where $g(n)$ is 12-periodic sequence?
For example $n^m,n \in \mathbb{N}, m=2k+1, k \in \mathbb{N}$ is 12-peridic in terms of $\pmod{12}$( $n^3 \equiv x_n \pmod{12}, \{x_n\}_{n=1}^{12} =[1,8,3,4,5,0,7,8,9,4,11,0]$. Can you find another one that is such that has not all numbers same as in example sequence?
The sequence $(x_n)$ is not given, but it has requirement of being 12-periodic and I'm looking for some other functions than $n^m,n \in \mathbb{N}, m=2k+1, k \in \mathbb{N}$ that generates 12-periodic sequence modulo 12 which has not all numbers same as in example sequence?.


text:
Q: java, selenium web driver This is the snapshot of Login popup :

I'm newbie in Selenium webdriver. I wrote this code to figure out navigate commands but once the browser opens, there is a login popup that is displayed. I tried to close it using classname or xpath but timeout exception occurs.
Do I need to use explicit wait in this case? Could you help me to figure out what the problem is?
public class TestNavigateCommands {
WebDriver driver;
public void invokeBrowser(){
    try {
        System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
        ChromeOptions options=new ChromeOptions();
        options.addArguments("start-fullscreen");
        driver=new ChromeDriver(options);
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
        navigateCommands();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
public void navigateCommands(){
    try {
        driver.navigate().to("https://www.flipkart.com/");
        Thread.sleep(4000);
        driver.findElement(By.className("2AkmmA _29YdH8")).click();
        //driver.findElement(By.xpath("//*[@class='_2AkmmA _29YdH8']")).click();
        driver.findElement(By.xpath("//span[starts-with(text(),'Applicances')]")).click();
        driver.findElement(By.xpath("//span[contains(text(),'Microwave Ovens')]")).click();
        Thread.sleep(2000);
        driver.navigate().back();
        Thread.sleep(2000);
        driver.navigate().forward();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    TestNavigateCommands test1= new TestNavigateCommands();
    test1.invokeBrowser();

}

}
Exception :

[43.366][SEVERE]: Timed out receiving message from renderer: 37.150
  [43.373][SEVERE]: Timed out receiving message from renderer: -0.007
  org.openqa.selenium.TimeoutException: timeout

A: public class TestNavigateCommands {
WebDriver driver;

public void invokeBrowser() {
    try {
        System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-fullscreen");
        driver = new ChromeDriver(options);
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
        navigateCommands();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void navigateCommands() {
    try {
        driver.navigate().to("https://www.flipkart.com/");
        driver.findElement(By.xpath("//div[@class='_3Njdz7']//button[@class='_2AkmmA _29YdH8']")).click();
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a[@title='Appliances']//span"))));
        driver.findElement(By.xpath("//a[@title='Appliances']//span")).click();
        Thread.sleep(2000);
        driver.navigate().back();
        driver.navigate().forward();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

A: Try this code it may help:
public class TestNavigateCommands {
     public static void main(String[] args) throws InterruptedException {
            try {
                  System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
                  WebDriver driver = new ChromeDriver();
                  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                  WebDriverWait wait=new WebDriverWait(driver,50 );

                  driver.manage().window().maximize();

                  driver.navigate().to("https://www.flipkart.com/");
                  driver.findElement(By.xpath("//button[contains(@class,'YdH8')]")).click();

                  wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a[@title='Appliances']//span"))));
                  driver.findElement(By.xpath("//a[@title='Appliances']//span")).click();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


text:
Q: How to parse csv file with comma in some fields I am using Sparklyr's function spark_read_csv to parse a csv file into Spark.
I have a csv file but some of columns have comma as their value and they are separated by quotation marks:
Here is a snapshot of my data:
100005870186,B,C,01NOV05,1,0,1,0,23,5.5,217876.2,1,"BANK OF AMERICA, N.A.",5.5,"223,000.00",

As you can imagine, if I use spark_read_csv() to read in and comma is treated as delimiter, "BANK OF AMERICA, N.A." will be parsed into two fields so does "223,000.00". Is there a way to parse this correctly?


text:
Q: Spivak, Ch. 5 Limits, Problem 3 vii: Prove a limit $l$ of a function by showing $\delta$ such that $|f(x)-l|<\epsilon\ \forall x:\ 0<|x-a|<\delta$ In Spivak, Ch. 5 on Limits, problem 3 we are asked to determine the limit $l$ for the given function and value of $a$, and to prove that it is the limit by showing how to find a $\delta$ such that $|f(x)-l|<\epsilon$ for all $x$ satisfying $0<|x-a|<\delta$.
The solution for this problem is not available in the solution manual.
Consider item $vii$, which specifies the function $f(x)=\sqrt{|x|}$ with $a=0$
Case 1: $\forall \epsilon: 0<\epsilon<1$
$$\implies \epsilon^2<\epsilon<1$$
$$|x|<\epsilon^2\implies \sqrt{|x|}<\epsilon$$
Case 2: $\forall \epsilon: 1\leq \epsilon < \infty$
$$\epsilon\leq\epsilon^2 \implies |x|<\epsilon^2\implies \sqrt{|x|}<\epsilon$$
Therefore
$$\forall \epsilon>0,|x-0|<\epsilon^2\implies|\sqrt{|x|}-0|<\epsilon$$
$$\implies \lim_\limits{x\to a} \sqrt{|x|}=0$$
Is this correct?

A: There is no need to consider two separate cases.
Given $\epsilon>0$, we pick $\delta =\epsilon^2>0$, if $|x-0|<\delta =\epsilon^2$, we take square root on both sides,
$$|\sqrt{|x|}-0|< \epsilon$$


text:
Q: How to create Redis cluster in DC/OS I was able to create a cluster of Redis instances in my local machine.
But I was wondering of how we can achieve this in Pass environment i.e. in DC/OS?
Any help will be very helpful.

A: If you're specifically looking at DC/OS, you can have a look at the example at https://github.com/dcos/examples/tree/master/redis which covers some of the basic components as you get started.


text:
Q: iterate over the properties of an object in JSTL, not an array list or collection I have a person object and was wondering if I can use JSTL to do something like this:
                        <c:forEach items="${user}" var="element">

                        ${element.firstname}
                        ${element.lastname}
                        ${element.age}

                    </c:forEach>

everything I've found so far points to collections or an array list.  user is stored as a session variable.
Is this possible?
Many thanks.

A: no its not possible to iterate an user object. you can iterate only collections. because it is a single object .


text:
Q: Unable to load CA private key when creating the intermediate pair Following the tutorial at LINK to create the root pair and intermediate pair.
Creating the root pair works fine, but when I try to create the intermediate pair using:
openssl ca -config openssl.cnf -extensions v3_intermediate_ca -days 3650 -notext -md sha256 -in intermediate/csr/intermediate.csr.pem -out intermediate/certs/intermediate.cert.pem

I get the following error:
Using Configuration from openssl.cnf
Can't open /root/ca/private/ca.key.pem for reading, No such file or directory
140382210524824:error:02001002:system library:fopen:No such file or directory:crypto/bios/bss_file.c:398:fopen('/root/ca/private/ca.key.pem','r')
140382210524824:error:20074002:BIO routines:BIO_new_file:no such file:crypto/bios/bss_file.c:76:
unable to load CA private key

The ca.key.pem file was encrypted using:
chmod 400 private/ca.key.pem

And I verified that I can see the CA's private key file using:
ls /root/ca/private/ca.key.pem

What is wrong?


text: Q: Does the interaction between 2 photons change its traveling directions? As I understand from the Hong-Ou-Mandle effect, the interaction between 2 photons is possible. Can 2 Photons interact with each other in free space? Suppose that the 2 photons met in the spacetime with same (frequency, phase, etc.); Will that affect the traveling direction of the 2 photons in spacetime after the interaction?


text:
Q: WP7 retrieving audio binary from database I have an issue with using FileStream to retrieve and use audio binary from Sql server database. I tried MemoryStream but wasn't working. Here's my codes for inserting the audio binary to the database using windows form.
        try
        {
            SqlCommand cmd = null;
            SqlParameter param = null;

            cmd = new SqlCommand("INSERT INTO Audio(audioBinary) VALUES(@BLOBPARAM)", conn);

            FileStream fs = null;
            fs = new FileStream("..\\..\\audio\\a3.mp3", FileMode.Open, FileAccess.Read);
            Byte[] blob = new Byte[fs.Length];
            fs.Read(blob, 0, blob.Length);
            fs.Close();

            param = new SqlParameter("@BLOBPARAM", SqlDbType.VarBinary, blob.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, blob);
            cmd.Parameters.Add(param);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

            MessageBox.Show("Successful");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

The code above worked perfectly fine, the problem occurs in retrieving and using the data at Windows Phone 7 Application. Addition, the data were retrieved from web service. This is my code for retrieving the binary data.
Assuming me1 is a MediaElement, the binary data is stored inside testImage.
        ArrayOfBase64Binary testImage = new ArrayOfBase64Binary();
        byte[] audioArr = new byte[1];
        FileStream fs = null;

        audioArr = testImage[0];
        text.Text = audioArr[0].ToString();

        fs.Write(audioArr, 0, audioArr.Length);

        me1.SetSource(fs);
        me1.Play();

I tried displaying the binary data in a TextBlock and it did return an integer but when trying to write it into the stream, an error occurred:

An unhandled exception of type 'System.NullReferenceException' occurred in test.dll

A: FileStream fs = null;

....

fs.Write(audioArr, 0, audioArr.Length);

You will get a NullReferenceException if you try to use a FileStream object that hasn't been allocated yet. Create a new FileStream object, before trying to write to it.


text:
Q: Using URL in a LaTeX bibtex file I'm using bibtex for my bibliography in LaTeX. I would like to use URL's and I need to cite. How do I add URLs into the .bib file. Also, I am using chicago as a bibliographystyle. I wrote the following code, but It does not show up in my refreneces. How can I fix it?
 \begin{filecontents*}{mybib1.bib}
 @misc{bworld,
 author = {Ingo Lütkebohle},
 title = {{BWorld Robot Control Software}},
 howpublished = "\url{http://aiweb.techfak.uni-bielefeld.de/content/bworld-
 robot-control-software/}",
 year = {2008},
 }
\end{filecontents*}

\usepackage{url}
\begin{document}

 The information is available in \citep{bworld}.

\bibliographystyle{chicago}
\bibliography{mybib1}
\end{document}

A:  Too long for a comment and needed markup
Compile the following code (saved as myfile.tex) with
pdflatex myfile
bibtex myfile
pdflatex myfile
pdflatex myfile

Contents of myfile.tex:
\documentclass{article}
\usepackage{filecontents}
 \begin{filecontents*}{mybib1.bib}
 @misc{bworld,
 author = {Ingo Lütkebohle},
 title = {{BWorld Robot Control Software}},
 howpublished = "\url{http://aiweb.techfak.uni-bielefeld.de/content/bworld-
 robot-control-software/}",
 year = {2008},
 }
\end{filecontents*}
\usepackage{natbib}

\usepackage{url}
\begin{document}

 The information is available in \citep{bworld}.

\bibliographystyle{chicago}
\bibliography{mybib1}
\end{document}


text:
Q: Using memory address as input I have a bunch of images in memory. I want to use the address of these images as input, so I can load them into matlab. I know I can use imread if I am not using memory address as input.
How can I do this?


text:
Q: Addition of 2 unsigned values in VHDL IEEE numeric_std : why this choice? In VHDL, the IEEE numeric_std package does not behave as one could expect. The addition of two unsigned values coded on 8 bits is not given on 9 bits, but on 8 bits.
What are the reasons of this choice ?

A: This "choice" allows the hardware designer to only handle overflow if it makes sense:

*

*Ignore the overflow
function add_ignore_ovf(a : unsigned(7 downto 0), b : unsigned(7 downto 0)) return unsigned(7 downto 0) is
begin
    return a + b;
end function;
One time this makes sense for implementing modulo 2 counters.

*Handle the overflow
function add_with_ovf(a : unsigned(7 downto 0), b : unsigned(7 downto 0)) return unsigned(8 downto 0) is
   variable a_ext, b_ext : unsigned(8 downto 0);
 begin
   a_ext := '0' & a;
   b_ext := '0' & b;
   return a_ext + b_ext;
end function;


text:
Q: Powering DSLR with buck/boost convertor I've been experimenting a bit with time-lapse photography lately. Still basic stuff. Right now I have to change batteries every so often which is a pain because it's hard not to move the camera when changing the batteries. I've used the ACK-E6 power adapter to run my camera from mains, but this is only possible in some situations.
So I'm looking to somehow attach some higher capacity batteries to my camera.
The regular batteries for my camera (LP-E6) deliver 7.2V. The specifications of the ACK-E6 mains adaptor list the output to the camera as 7.6V 3A.
I've read some things about buck/boost regulators (but I'm hardly an electrical engineer) that I can use to regulate the voltage to that desired 7.2V for my camera.
The goal is to attach a 12V car battery, but have other (smaller, lower weight) options if needed.
I was thinking of buying this buck/boost regulator (or one like this):
3A Power Adapter DC 3.8-32V to 1.3-35V Automatic Buck/Boost Voltage Regulator 3A Drive Power Supply #090040
http://www.aliexpress.com/item/5-PCS-LOT-3A-Power-Adapter-DC-3-8-32V-to-1-3-35V-Automatic-Buck/1609180228.html
I guess the numbers add up, and this should work. But I'm not really sure about the possible risks, because I don't want to damage my camera.
I've searched a lot but I can't really seem to find an answer, so that's why I'm asking here.
Is there a possibility that the 12V from the input goes straight to the output? Are there other risks I have to take into account before attempting this?

A: In principle, what you want to do will work. But as you say, it's a matter of risk and peace of mind. It is possible, though unlikely, that the unit you are considering (and widely available for almost nothing on ebay) could fail in such a way as to deliver a damaging voltage to the camera, which would be expensive to fix.
The main situation to avoid is over voltage. To avoid that you could add a crowbar circuit (see google if interested), but that seems like work.
The other issue is whether or not the camera presents a highly variable load, as Dave suggests. In that case the 3A rating on the ACK-E6 may be an average that doesn't represent the peak required, which the capacitors on your regulator board may not be sufficient to supply.
A possible workaround for both these problems is to take your existing ACK-E6 and interpose a connector between the brick and the "battery" block. Connect the brick for mains power, and instead connect your DC-DC converter (set to 8V I think from the spec) for alternate power.  The ACK-E6 spec suggests that there's some active regulation in the "battery" block, and that would help moderate any over-voltage accident, and I would expect provide sufficient capacitance to handle transient demand.
But all of this is somewhat speculative without schematics!

A: Should be no problem. I build aerial photography camera pods for one of my clients, and I use a switching converter to power the cameras from the 12V/24V aircraft power. My design is based on the LM25005, but pretty much any chip that can handle the current (and beware of the spike drawn when the shutter fires!) should be fine. I use a separate converter for each camera.


text:
Q: MySQL - Retrieving data without duplication So in my SQL table I have this situation.
One item (that has a unique ID) can have photos associated with it.
I need to get all of the information on an item and both of the photos in one record (or row to be more precise).
My current query is:
SELECT ultrait_wpl_properties.id, location1_name, location3_name, location4_name, field_312, field_42, post_code, lot_area, living_area, price, bedrooms, bathrooms, field_308, googlemap_lt, googlemap_ln, street, street_no, ultrait_wpl_property_types.name, property_title, build_year, add_date, ultrait_wpl_items.item_name
    FROM ultrait_wpl_properties
    JOIN ultrait_wpl_property_types ON ultrait_wpl_properties.property_type = ultrait_wpl_property_types.id
    JOIN ultrait_wpl_items ON ultrait_wpl_properties.id = ultrait_wpl_items.parent_id
    ORDER BY ultrait_wpl_properties.id ";

From this query i get all of the information I need and the picture. The issue with my current approach is if there is more than one picture i get a duplicated row when my query executes. Is there a way around this?
I ask as I later use this data and export it to an xml file but because this query returns a duplicate record per every photo. An XML file with one item but 5 pictures will return 5 identical nodes but with different image URLs.

A: rewrite your query as follows
SELECT DISTINCT
    ultrait_wpl_properties.id,
    location1_name,
    location3_name,
    location4_name,
    field_312,
    field_42,
    post_code,
    lot_area,
    living_area,
    price,
    bedrooms,
    bathrooms,
    field_308,
    googlemap_lt,
    googlemap_ln,
    street,
    street_no,
    ultrait_wpl_property_types.name,
    property_title,
    build_year,
    add_date,
    ultrait_wpl_items.item_name
FROM
    ultrait_wpl_properties
INNER JOIN
    ultrait_wpl_property_types ON
        ultrait_wpl_properties.property_type = ultrait_wpl_property_types.id
INNER JOIN
    ultrait_wpl_items ON
        ultrait_wpl_properties.id = ultrait_wpl_items.parent_id
ORDER BY
    ultrait_wpl_properties.id

A: You could try this.
   SELECT ultrait_wpl_properties.id,
          (all those other columns),
          GROUP_CONCAT(ultrait_wpl_items.item_name) items
     FROM  ultrait_wpl_properties
    INNER JOIN ultrait_wpl_property_types
              ON ultrait_wpl_properties.property_type = ultrait_wpl_property_types.id
     LEFT JOIN ultrait_wpl_items
              ON ultrait_wpl_properties.id = ultrait_wpl_items.parent_id
    GROUP BY ultrait_wpl_properties.id

It uses the notorious non-standard GROUP BY extension in MySQL, so it might yield slightly strange results. But it will yield a comma-separated list of your item_name columns for each id.
The LEFT JOIN makes it work correctly for id values lacking any images.


text:
Q: Bad operand types for binary operator '| |' first type: int; second type: int. What does this mean? When trying to compile i'm being given the error message: Bad operand types for binary operator  '| |' first type: int; second type: int.
This is the code i have written, although it isn't finished.
public class Main
{
    public static void main ( String [] args )
    {
        int squareSize = BIO.getInt();

        for(int row = 0; row == squareSize; row++)
        {
            if (row = 1 || row = squareSize)
        { for(int stars = 0; stars <=squareSize; stars++)
            System.out.print("*");

    }
}

Please could you tell me what this means and how i can fix it?

A: if (row = 1 || row = squareSize)

= is an assignment operator, not a equality/relational operator.
I think you want ==:
if (row == 1 || row == squareSize)

A: Change if (row = 1 || row = squareSize) to if (row == 1 || row == squareSize).
What is happening now is you are doing assignments to the variable row and then ORing the numbers together, which is wrong.

A: Don't be confused between = and == operators :
if (row == 1 || row == squareSize)

= is used to assignate a value to a variable, whereas the second is used to process a logical comparison between two variables.

A: need to use == not =
if (row == 1 || row == squareSize)


text:
Q: Does product measure being ergodic imply component ergodic? Suppose $(X,B,\mu,T)$ is measure preserving dynamical system.
Consider a singleton set $\{0\}$ with counting measure, and suppose $S:X\times \{0\}\to X\times \{0\}$ defined by $S(x,0)=(Tx,0)$ is ergodic wrt the product measure.
Then can we say $T$ is ergodic?
I think the answer should be yes, but there seem to be some gaps:
if $f:X\to \mathbb{R}$ is measurable wrt $\mu$ and $f\circ T= f$, then I suppose the idea would be to consider $g:X\times \{0\}\to \mathbb{R}$ defined by $g(x,0)=f(x)$. This clearly satisfies $g\circ S= g$, and so $g$ is constant almost everywhere with respect to the product measure.
However, I am unsure on how to pass to the original measure (I am not even sure if my $g$ as defined is measurable. The counting measure is throwing me off!). So I suppose those are the two questions:
1) Is my $g$ measurable?
2) How can I "clinch" the proof?
Thanks in advance!

A: $g$ is surely measurable. If $(\mu \times \nu )(A)=0%=$ the there exists $y$ such that the  'section' $A^{y}=\{x: (x,y) \in A\}$ satisfies $\mu (A^{y})=0$ (by Fubini's Theorem). This proves that $f$ is a constant a.e. $[\mu]$.


text:
Q: Any chart gantt chart displaying incorrect date in timeline Gantt chart
In any chart wrong date is showing as you can see from the image, 14th March is the actual date given but the output is displaced by 1 and showing 13th March.
I googled all over and found nothing


text:
Q: Sharing Android NDK Lib The Native Code of the Android application is going alone with application as lib file in the APK file. Suppose if I want to share a native code between two different applications, Is there any trick avail apart from the below:

*

*Adding the lib with every application

*Copy the lib in to system/lib folder and dynamically link it with application. (If we build just only the applications then we cannot use this).

A: You can't copy anything onto /system unless you are root, so I'd suggest you just include your native library in every application that needs it.

A: You must create library project ant than create your activity and lib.so file. You may be added all project this library.(Such as vitamio)


text:
Q: add core data image to collection view cell I have a collection view. I want to fill each cell with the images that are stored in the apps core data. However the cells only fill with the last image that was taken.
not each individual cell benign filled with each individual image.
my code is as follows:

*

*when the user takes a photo it is compressed and stored in core data:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    picker.dismiss(animated: true)

   guard let image = info[.editedImage] as? UIImage else {
       print("No image found")
       return
   }
   // print out the image size as a test
   print(image.size)

   //convert image to savable type for coredata
   var jpegImageData = image.jpegData(compressionQuality: 1.0)
   jegImage = jpegImageData!

   //calling function in coredataManger to save image in data format
   CoreDataManager.sharedInstance.addImage()

}

*The adding to core data function that was activated above:
func addImage() {
let entityName =  NSEntityDescription.entity(forEntityName: "ImageData", in: context)
let image2 = NSManagedObject(entity: entityName!, insertInto: context)
image2.setValue(jegImage, forKeyPath: "imageName")
do {
  try context.save()
    print("image is saved")
} catch let error as NSError {
  print("Could not save. \(error), \(error.userInfo)")
}
}

*ive global variables to pass images from one VC to another
 //global variables for images saved to core data
 var jegImage = Data()
 var theImagePulled = UIImage()

*Trying to populate the collection view cell with the images stored in core data:
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeRoomCell", for: indexPath) as! HomeRoomCell
     let name = cartoonArr[indexPath.item]

     //setting image shown in the colleciton view equal to the gloabl images stored in core data
     let image = theImagePulled
     cell.bindData(name: name, image: image)
     return cell
 }

So the problem is that the cell gets populated but they all populate with the same image. this image is the last image that was added to core data model, even though there are several images in the core data model. I have been playing around with trying to set up an array that stores all these core data images but i can't figure it out. any ideas?

A: Get rid of the global variables, which are indeed capturing the most recent image.
Use NSFetchedResultsController in your collection view.
If you're new to Core Data, you might consider passing just a string around and displaying that, first. Then move on to images.


text:
Q: Can dynamically generating an HTML table in ASP.net cause significant performance issues? I am working on a page with several dynamically generated tables where the original developers used approximately the following logic:

...

  <asp:PlaceHolder ID="ph1" runat="server" />

In the code behind:
// Do lots of stuff
HtmlTableCell cell = new HtmlTableCell();
// set cell text, formatting, etc
ph1.Controls.Add(cell);
// repeat the above logic for every cell in the table

In one page, methods like this are used to add up to 10-15 total rows, with 10-15 columns each spread over 4-5 tables. The table structures are set, so this could also be constructed by hard-coding the table structure in html and putting literals and labels in each cell. The page itself has some performance issues. This is one of the factors that could be contributing to the bad performance.
The question is:

*

*Is dynamically creating this many table cells and building the table in the code behind versus hard-coding the table and using Literals/Labels for populating the data something that could be introducing big performance issues (ie: is it worth switching over)?

*Or is it more accurate to say that in a situation like this, it would not be so significant (or at least not significant enough to warrant the hours it would take to rewrite the dynamic table generation into hard coded table + Literals)?

A: It's not ideal, but I suspect that the real issue is the datasource that feeds that logic.  Speed up whatever query it uses to get the data.

A: *

*If they are they must be so marginal that you wouldnt notice. Ive coded a gridviewish control in this way with 10x50 cells and had no noticeable performance issues compared to static tables in similar size.

*What you should strive for in most cases is maintainability :)

A: Short answer:  highly unlikely.
Long answer:  It really depends on your definition of "significantly".  Assuming you are generating a typical HTML page on a decent server machine with a fast connection, the breakdown would go something like this:

*

*load data from data source: 50-300ms

*generate 1125 table cells (15 x 15 x 5): 50-100ms

*assemble HTML document: 10-20ms

*send HTML page over internet: 150-1000ms

*render HTML page in browser: 50-500ms

The numbers are obviously estimates -- the important point is the cost of step (2) in relationship to all the others.  Spending time optimizing step (2) when it constitutes a small share of the total cost is not a good use of developer time.  As CodeSpeaker said, clean and maintainable code is a far better investment.  If the total time to load the page is really an issue, attack the dominant costs first (steps 1 and 4) before moving on to the rest of the pipeline.

A: This code would not be signficantly enhanced in performance by using literals (in either direction) and with the volumes you mention I doubt you could even measure the difference.

A: Yaakov, I'd worry more about what happens on the client side with such rendered code. I mean... it depends on HOW do you setup cell rendering (formatting, CSS, classes/ids) for each individual cell.
If you end up with large class names / ids and inline CSS!!!, then you should look into manually generating the table structure (without even using literals). It looks to me that all of those tables contents are just text so you could render it naturally without any kind of control overhead.


text:
Q: How to open form when a specific cell in DataGridView Single-click in vb.net? +-------+-------+-------+-------+
|   a   |   b   |   c   |   d   |
+-------+-------+-------+-------+
|   1.  |   b1  |   c1  |   d1  |
+-------+-------+-------+-------+

The problem is how to make a cell ex: b1 click and a form will show? but when c1 or d1 clicked the form won't open, the only cursor on the place c1 or d1.
I already use CellClick event but all of the cells when I click will open the form, that's not what I want. I use VB.NET.

A: Just use the _CellMouseUp event like:
Private Sub DataGridView1_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseUp
    Dim i As Integer
    Dim j As Integer
    i = DataGridView1.CurrentCell.RowIndex
    j = DataGridView1.CurrentCell.ColumnIndex
    If i = 5 And j = 2 Then
        MsgBox(i & "  " & j)
    End If
End Sub

A: Use the DataGridViewCellEventArgs. They are passed to the click event as e. The index of the first row of data (not including the headings) is 0. The colums are also indexed starting with 0. So, in your diagram column c would be index 2. You will find that .net indexes start at 0.
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    If e.RowIndex = 0 AndAlso e.ColumnIndex = 2 Then
        Form2.Show()
    End If
End Sub