text:
Q: Can't build with Cmake I am new to Cmake and I am trying to create a CMakeLists.txt to build my project. I can build my project from command line using g++ compiler but when it comes to Cmake I am confused.
The directory structure is like this :
Project_folder
   |--> Source
       |--> main.cpp
       |--> file1.cpp
       |--> file2.cpp
   |--> Header
       |--> header1.h
       |--> header2.h
   |--> build (from where I run cmake .. and make)
       CMakeLists.txt (this is under Project_folder)
Dependencies
   |--> utils
       |--> Utils.cpp
   |--> include (has many folders in here)
   |--> build (this path is in LD_LIBRARY_PATH as well)
       |--> sharedlib1.so
       |--> sharedlib2.so

Now from within the Project_Folder I can successfully run :
g++ ./Source/main.cpp ./Source/file1.cpp ./Source/file2.cpp ../Dependencies/utils/Utils.cpp -I ../Dependencies -I ../Dependencies/include/ -I ./Header/ -L ../Dependencies/build -std=c++11 -lsharedlib1 -lsharedlib2 -o ./build/main `pkg-config opencv --cflags --libs`

and generate the executable file.
Now I want to configure a CMakeLists.txt and try to replicate what the above compiler line is doing but with no success (I can cmake .., but I cannot make). CMakeLists.txt looks like this :
cmake_minimum_required(VERSION 2.8.9)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

project(my_project)

#For the shared library:
set ( PROJECT_LINK_LIBS sharedlib1.so sharedlib2.so)
link_directories(${PROJECT_SOURCE_DIR}/../Dependencies/build/ )

include_directories(${PROJECT_SOURCE_DIR}/../Dependencies ${PROJECT_SOURCE_DIR}/../Dependencies/include ${PROJECT_SOURCE_DIR}/Header)
file(GLOB SOURCES "Source/*.cpp" )

set(CMAKE_CXX_FLAGS_RELEASE pkg-config opencv cflags libs)

## add_executable(name_of_output.o list_of_cpp_files)
add_executable(build ${SOURCES})

Running make after generating the makefile I get undefined reference to everything inside main.cpp. Is there anything obvious in the CMakeLists.txt that I should change?

A: Your call to g++ includes the ../Dependencies/utils/Utils.cpp file, but your call to add_executable is only using the files matched by Source/*.cpp. A quick solution would be to add ../Dependencies/Utils.cpp to the call to add_executable() making it
add_executable(build ${SOURCES} "${PROJECT_SOURCE_DIR}/../Dependencies/Utils.cpp")

On a related note: CMake discourages using file(GLOB ...) to get a list of source files, it's generally better to list the source files explicitly

A: You should use target_link_libraries after add_executable.
Please check the examples:

*

*Executable with Static Library

*Executable with Shared Library
While running the application you will also get some errors. Please be aware of RPATH.

A: Ok I managed to solve it ! :)
# set Cmake minimum version to use
cmake_minimum_required(VERSION 2.8.9)

# set the compiler
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

# name your project
project(my_project)
set(CMAKE_BUILD_TYPE Release)

# Find and load the settings from the packages
find_package(PkgConfig REQUIRED)
find_package(OpenCV REQUIRED )

# set the extra flags
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -cflags -libs")

# set the shared libraries name (where the libraries are libsharedlib1.so and libsharedlib2.so + opencv runtime libraries)
set(PROJECT_LINK_LIBS sharedlib1 sharedlib2) ${OpenCV_LIBS}

# include the header files (.h)
include_directories(${PROJECT_SOURCE_DIR}/../Dependencies ${PROJECT_SOURCE_DIR}/../Dependencies/include ${PROJECT_SOURCE_DIR}/Header)

# add the source files (.cpp) using the set command as follow
set(SOURCES
Source/main.cpp
Source/file1.cpp
Source/file2.cpp
${PROJECT_SOURCE_DIR}/../Dependencies/utils/Utils.cpp)

# link the shared libraries (/build/libsharedlib1.so and /build/libsharedlib2.so)
link_directories(${PROJECT_SOURCE_DIR}/../Dependencies/build/)

# add_executable(name_of_output list_of_cpp_files)
add_executable(main ${SOURCES})

# link the executable with the shared libraries
target_link_libraries(main ${PROJECT_LINK_LIBS} )

and finally ./main will run the program !


text:
Q: Practical example for Immutable class It is obvious that immutability increases the re-usability since it creates new object in each state change.Can somebody tells me a practical scenario where we need a immutable class ?

A: Consider java.lang.String. If it weren't immutable, every time you ever have a string you want to be confident wouldn't change underneath you, you'd have to create a copy.
Another example is collections: it's nice to be able to accept or return a genuinely immutable collection (e.g. from Guava - not just an immutable view on a mutable collection) and have confidence that it won't be changed.
Whether those count as "needs" or not, I don't know - but I wouldn't want to develop without them.

A: A good example is related to hashing.  A class overrides the equals() and hashCode() methods so that it can be used in data structures like HashSet and (as keys in) HashMap, and the hash code is typically derived by some identifying member attributes.  However, if these attributes were to change then so would the object's hash code, so the object is no longer usable in a hashing data structure.

A: Java provides a nice example: String.

A: This article has a good color example (since color definitions don't change).
http://www.ibm.com/developerworks/java/library/j-jtp02183/index.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rpyc: one client to many servers How do I connect the same client to many servers?
I've tried:
c0 = rpyc.classic.connect(ip0)
async_update0 = rpyc.async(c0.modules["some_module"].some_function)
async_result0 = async_update0()

c1 = rpyc.classic.connect(ip1)
async_update1 = rpyc.async(c1.modules["some_module"].some_function)
async_result1 = async_update1()

But only the later one is actually being done when I do async_result0/1.wait().


text:
Q: what will bw the output of this code? c++ #include <iostream>

using namespace std;

int f(int i){
  int k=0;
  if(i>0)
    {
        int k=i*10;
    }
    else {
        int k= i++;
    }
    cout <<k;
    return i;
}

int main()
{
    cout << f(1);
    cout << ".";
    cout << f(0);

    return 0;
}

This is the code, compiler shows "01.01" which i quite don't understand, any help will be very much welcomed!

A: int k = i * 10; and int k = i++; are declarations of k that shadow the outer k. The statement std::cout << k; in the outer scope therefore always outputs zero.
The only effect of the if body is to increase i by 1. And it only does that if i is zero (or less). That value of i is returned printed.
Thus the output is 01.01. Armed with a line by line debugger, the shadowing effect will be obvious.


text:
Q: Average Velocity Would someone mind checking my work as my answer differs from the book and I think the book is incorrect.
starting point: $S=4t^3$
$t1 = 0$
$t2 = .1$
$t1 = 4(0)^3 = 0$
$t2 = 4(.1)^3 = .004$
$(.004-0)/(2-1) = .004/1 = .004 m/s$
While the book has $.04 m/s$

A: $$\frac{s(t+\Delta t)-s(t)}{\Delta t} = \frac{s(t_2)-s(t_1)}{t_2-t_1} = \frac{s(.1)-s(0)}{.1} = \frac{.004-0}{.1} = .04 \text{m/s}$$
You have used the wrong time difference.


text:
Q: Chart.js - get x-axis label (or index) in onHover event Is there a way to get the x-axis label (or index since not every step is labelled) in the onHover event? I know about getElementsAtEventForMode, getElementsAtXAxis, getElementAtEvent, etc. But I don't want the elements. I just want to know where along the x-axis the mouse is at that point.

A: onHover: function (evt) {
    const rect = canvas.getBoundingClientRect();
    var x = evt.clientX - rect.left;
    if (x > myChart.chartArea.right)
        x = myChart.chartArea.right;
    const dataX = myChart.scales["x-axis-0"].getValueForPixel(x);
}


text:
Q: Force inversely proportional to the squared distance Newton's law of universal gravitation:
"Newton's law of universal gravitation states that every point mass in the universe attracts every other point mass with a force that is directly proportional to the product of their masses and inversely proportional to the square of the distance between them."
Coulomb's law:
"The magnitude of the Electrostatics force of interaction between two point charges is directly proportional to the scalar multiplication of the magnitudes of charges and inversely proportional to the square of the distances between them."
How did Sir Isaac Newton and Sir Charles Augustine De Coulomb come to know that the force, gravitational or coulomb's,  is inversely proportional to the square of the distance between two point masses or charges, why didn't they just say that the force is inversely proportional to the distance of two bodies from each other or two charges? There must have been something that made them formulate these inverse-square laws.

A: The short answer is "observations".
In the case of the gravitational law, the orbits of the planets around the sun, the moon around the earth fit mathematically  a force  with an inverse square law for the distance. An inverse law does not.
In the case of electricity this article points out the observational history:

Early investigators who suspected that the electrical force diminished with distance as the gravitational force did (i.e., as the inverse square of the distance) included Daniel Bernoulli 1 and Alessandro Volta, both of whom measured the force between plates of a capacitor, and Aepinus who supposed the inverse-square law in 1758.

and then others took it from there to end up with the comprehensive publications of Coulomb, based on measurements.

Finally, in 1785, the French physicist Charles Augustin de Coulomb published his first three reports of electricity and magnetism where he stated his law. This publication was essential to the development of the theory of electromagnetism.[8] He used a torsion balance to study the repulsion and attraction forces of charged particles and determined that the magnitude of the electric force between two point charges is directly proportional to the product of the charges and inversely proportional to the square of the distance between them.

A: Actually, the idea of the inverse-square law predated Newton (or at least Newton's publications on the topic) by at least a little bit. Robert Hooke proposed that gravity obeyed it before Newton did so. His reasoning was inspired by geometric considerations and light. If you have a point source of light, the power passing through a sphere centered on the point will be constant. If the point is emitting equally in all directions, you can conclude that the power per unit area, or intensity, will fall off as $1/r^2$, and this was known for a while. Basically, the power of $2$ comes from the fact that spheres' areas grow with that power of radius, which comes from the fact that space has $2+1 = 3$ dimensions.
It is somewhat natural then to imagine a conserved quantity coming from a source, evenly distributed over a sphere. It's influence on a test particle is just determined by what intercepts the test particle, so the influence drops off as the quantity is distributed over larger and larger surfaces.

By the way, Newton never gave Hooke much credit for this idea. Hooke, not having the tools available to do anything with it (unlike Newton, who proved that Kepler's empirical laws follow immediately from an inverse-square law), received less recognition than he thought he deserved. This rivalry led to Hooke teaming up with Leibniz against Newton, and the debate grew to encompass calculus, philosophy, and an entire continent's worth of academics.

A: Historically, Isaac Newton was of course the first man who discovered the inverse square law and Coulomb just copied it from Newton. Electrostatic and gravitational fields both follow the $1/r^2$ law because in some regime, they're described by the same mathematical equation $\Delta \Phi = \rho$. In plain English, these laws indicate the field lines have to be shared by (i.e. diluted to) the area $4\pi r^2$ of a sphere which is why the intensity has to drop as $1/4\pi r^2$. This is really the "heuristic" explanation why the law is $1/r^2$ in a three-dimensional space. In a 9-dimensional space, it would be $1/r^8$ and so on.
Isaac Newton originally determined the inverse square law from two independent but closely related considerations, almost at the same moment. One of them was a comparison of the motion of bodies near the Earth and the motion of the Moon. The other one were Kepler's laws for planetary orbits.
Concerning the Moon-ball analogy, he could have figured out that the Moon is 60 times further from the Earth's center than objects on the Earth's surface (360,000 km vs 6,000 km). He translated this ratio to a ratio of the forces that must act on the objects at these two distances to yield the right ratio of periodicities, and figured out that the forces' ratio is 1-to-3,600 and the law is therefore $1/r^2$.
The other method – which is nearly equivalent (and mainly differs by having the Sun instead of the Earth as the source of gravity at the center) – used Kepler's third law. Kepler was able to deduce the exact orbits of the planets (including the timing) from Tycho Brahe's meticulous observations and extract the phenomenological laws. The third one says that $T^2\sim a^3$: the squared period of the orbit is proportional to the third power of the greater semi-axis of the elliptical orbit. When one studies circular orbits, it's straightforward to prove that this power law relating the period and the radius is equivalent to the $1/r^2$ power law in the force. You're invited to check it yourself; if you're missing some maths to do so, I am afraid that my reproduction of the proof wouldn't be any helpful, anyway.
Let me give you the derivation, anyway. The centripetal force (and acceleration), like the opposite centrifugal one, goes like $r\omega^2\sim r/T^2$ where $T$ is the period and $r$ is the radius of the circular orbit. Because Kepler determined $T^2\sim r^{3}$ in his third law, $r/T^2$ goes like $r/r^3=1/r^2$ and that's it: I derived that the acceleration (and therefore force) that has to act on the planet has to go as $1/r^2$.
(Note that if you wanted $1/r$, the third Kepler's law would have to say $T^2\sim r^2$ i.e. $T\sim r$. This proportionality would be equivalent to constant velocities of the planets, regardless of their distance from the Sun. That's indeed how things would work if space had 2 spatial dimensions but the real-world Solar System and similar systems just don't work like that: the speed of nearby planets is higher.)


text:
Q: trouble with sending mail with Spring mail through somain registrar 1and1 smtp I'm trying to send an email from a spring boot application with spring mail (1.5.8.RELEASE) JavaMailSender
sending through gmail SMTP is fine. however sending email through my domain registrar's amtp (registrar name- 1and1, in case someone already worked this out) is not working.
I'm getting this error, which imo - is more generic than useful:
com.sun.mail.smtp.SMTPSenderFailedException: 550-Requested action not taken: mailbox unavailable
550 invalid DNS MX or A/AAAA resource record
domain I'm sending through is bank.org, and has this DNS settings:
bank.org.             3600    IN      A       178.79.161.205
bank.org.             3600    IN      MX      11 mx01.1and1.com.
bank.org.             3600    IN      MX      10 mx00.1and1.com.

the issue is, I'm able to send emails to gmail with the settings specified in this guide:
http://www.baeldung.com/spring-email
these are settings to send with gmail:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<login user to smtp server>
spring.mail.password=<login password to smtp server>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

However when i try to send messages via my registrar these settings are not successful:
spring.mail.host=smtp.1and1.com
spring.mail.port=587
spring.mail.username=username
spring.mail.password=password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

thew issue is - I am able to connect to the 1and1 SMTP using thunderbird email client. so I know the credentials are working.
I guess what I need is to find out a way to detect the correct settings because the support team can't assist with issues related to sending email programmatically from spring mail

A: the cause of the issue was  - I didn't programmatically set the sender field (The "From" field)  in my outgoing message
Once i set the From field the issue was resolved.
unfortunately the response from 1and1's SMTP was irrelevant ("550 invalid DNS MX or A/AAAA resource record")
Hope this helps anyone


text:
Q: Django get fields of ForeignKey object in models I have these two models defined with a one to many relationship
from django.core.validators import RegexValidator
   from django.db import models
class Template(models.Model):
    name = models.CharField(max_length=100)
    fields = models.IntegerField()

    def __str__(self):
        return self.name

class Page(models.Model):
    template = models.ForeignKey(Template, related_name='pages')

    title = models.CharField(max_length=100)

    text = []

    for i in range(template.fields):   #Error occuring here
        text[i] = models.TextField()

    def __str__(self):
        return self.title

I want to get the value of template.fields, but I get this error
for i in range(template.fields):
AttributeError: 'ForeignKey' object has no attribute 'fields'

Am I using the ForeignKey Object wrong? Any help would be much appreciated

A: You can't get data to iterate template field. If you modify it,use __init__ function.
class Template(models.Model):
    name = models.CharField(max_length=100)
    fields = models.IntegerField()

    def __str__(self):
        return self.name

class Page(models.Model):
    template = models.ForeignKey(Template, related_name='pages')

    title = models.CharField(max_length=100)

    text = []

    def __init__(self, request, *args,**kwargs):
        super (Page,self ).__init__(*args,**kwargs)
        self.fields['template'].queryset = Template.objects.all()

    def __str__(self):
        return self.title


text:
Q: Failing to build my project due to Null safety issues in Dart I have been away from Flutter and Dart for some month now but when I saw that Flutter 2 was released I decided to update one of my Flutter projects. Super cool evertything and I just love Flutter and Dart.
Now I have run in to a null safety issue.
Dart is complaning on a method and I get when building the project.
Error: A non-null value must be returned since the return type 'String' doesn't allow null.

The method that it complains about
static String _fmt(String fmt, Object? val, int maxlen) {

  if (null == val) {
    return '';
  }

  // -- Ad support for thousand separators. --
  if (fmt.startsWith('%,') && fmt.endsWith('d')) {
    int i = val as int;
    val = i.toThousandString(',');
    fmt = '%${fmt.substring(2, fmt.length - 1)}s';
  }
  String s = sprintf(fmt, [val]);

  // -- Truncate if text overflows. --
  if (s.length > maxlen) {
    s = s.substring(0, maxlen);
    if (s.length > 1) {
      return s.substring(0, s.length - 2) + '..';
    } else if (s.length > 0 ) {
      return s.substring(0, s.length - 1) + '.';
    }
  } else {
    return s;
  }
}

The code is ugly but except for that I can't see that anything in this method could return null.
Or am I stupid?

A: Your problem is that not all of your code paths return a value:
if (s.length > maxlen) {
    s = s.substring(0, maxlen);
    if (s.length > 1) {
      return s.substring(0, s.length - 2) + '..';
    } else if (s.length > 0 ) {
      return s.substring(0, s.length - 1) + '.';
    }

    // Nothing will be explicitly returned if control flow reaches here.

  } else {
    return s;
  }

Previously this meant implicitly returning null.  Add a return value there or adjust your logic so that all possible paths are covered.
(Now, maxlen probably is expected to be non-negative, which would make it impossible to hit that control path in practice, but there's no way for the analyzer to know that.)


text:
Q: my Cnn Output looks like a normal curve distribution, but should look like a half normal curve I am developing an CNN combined with LSTM, and I am trying to reach an output distribution curve more similar to the original data that is a half normal curve. I think that changing the activation function could help but not getting the desired result.
Here is my Code
model3 = tf.keras.models.Sequential([
        tf.keras.layers.InputLayer((12, 48)),
        tf.keras.layers.Conv1D(filters=32, kernel_size=8,strides=1, padding="causal",activation='elu'),
        tf.keras.layers.MaxPooling1D(pool_size=2),
        tf.keras.layers.BatchNormalization(),
        #tf.keras.layers.ReLU(),
        tf.keras.layers.Conv1D(filters=64, kernel_size=4,strides=1, padding="causal",activation='elu'),
        tf.keras.layers.MaxPooling1D(pool_size=2),
        tf.keras.layers.BatchNormalization(),
        #tf.keras.layers.ReLU(),
        tf.keras.layers.Conv1D(filters=128, kernel_size=2,strides=1, padding="causal",activation='elu'),
        tf.keras.layers.MaxPooling1D(pool_size=2),
        tf.keras.layers.BatchNormalization(),
        #tf.keras.layers.ReLU(),
        tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64,return_sequences=True)),
        tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(128,  return_sequences=False)),
        tf.keras.layers.Dense(128, 'tanh'),
        tf.keras.layers.Dense(64, 'tanh'),
        #tf.keras.layers.Dropout(0.5),
        tf.keras.layers.Dense(16, 'tanh'),
        #tf.keras.layers.Dropout(0.5),
        tf.keras.layers.Dense(2, 'linear')]);

callbacks = [
    tf.keras.callbacks.ModelCheckpoint(
        "best_model.h5", save_best_only=True, monitor="val_loss"
    ),
    tf.keras.callbacks.ReduceLROnPlateau(
        monitor="val_loss", factor=0.5, patience=20, min_lr=0.000001
    ),
    tf.keras.callbacks.EarlyStopping(monitor="val_loss", patience=50, verbose=1),
    plotLog
]

model3.compile(loss=tf.keras.losses.MeanSquaredError(), optimizer=tf.keras.optimizers.Nadam(learning_rate=0.0001), metrics=[tf.keras.metrics.RootMeanSquaredError()])
history=model3.fit(
      X_train,
      y_train,
      validation_data=(X_val, y_val),
      epochs=150,
      callbacks=callbacks)
      #batch_size=32)

The fit process

Blue histogram represents the original Y, and the Green represents the predicted.
Both are on test_data (training/validate/test)


text:
Q: How to store large, multi-line text in SQL Server? What would be the best way to store a large amount of text in a Database? I would expect about 2500 words and since on average each word in English is around 6 characters, I expect over 15000 characters. This text may be non-English so I guess I would need Unicode to support everything.
This text needs to be inserted, retrieved, and also searched by keywords.
Maxwell.

A: You should use NVARCHAR(MAX) as the datatype for that particular column in question. Also, I would suggest you have a FULLTEXT INDEX on that column since you said that column will also include searching by keywords.

A: You need to use NVARCHAR(MAX)
You can store..
1 billion, 73 million, 741 thousand and 823 characters

A: If you will insert non-english characters you have to use NVARCHAR, and also when inserting the data you have to prefix it with an N like this:
CREATE TABLE tmp( description NVARCHAR(MAX) )
INSERT INTO tmp VALUES (N'Добро...')


text:
Q: Проблема с обрещениям к таблице Это запрос к БД, на выборку сообщения, которые пользователь отправил другим пользователям.
Проблема в том, что мне надо достать имя и фамилию, а они находятся в другой таблице.Под именем(datacenter).
id_finish(id человека которому отправляется сообщения) это внешний ключ к полю id таблицы datacenter.
В datacenter есть поля name, surname, которые мне нужно как-то включить в этот цикл
То есть как мне сделать что-бы $row[4]; и $row[5]; имели name and surname с таблицы datacenter
    $select = mysql_query("SELECT id, text, avatar, id_finish,  FROM massage WHERE id_start = '$id'");

  while ($row = mysql_fetch_array($select))
    {
  echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
    }

A: Соединение:
SELECT id, text, avatar, id_finish, name, surname  FROM massage m join datacenter d
on d.id = m.id_finish WHERE id_start = '$id'


text:
Q: Как добавить скрипт с другого сайта во Vuejs? Вот например на сайте яндекса есть такое. Npm пакета я не нашел, и где скачать нормальные форматированые.js файлы я тоже не нашел. Как в итоге подключить это во Vue?
Подключите скрипт блока.

<script src="https://yastatic.net/es5-shims/0.0.2/es5-shims.min.js"></script>
<script src="https://yastatic.net/share2/share.js" async="async"></script>

А как это подключить во Vue?

A: Если вы не хотите, вставлять данные скрипты в index.html и вам, допустим, надо чтобы эти скрипты подключались при загрузке конкретного компонента, в хуке жизненного цикла mounted() этого компонента вы можете их вставить, таким образом:
    const insertScript = document.createElement('script')
    insertScript.setAttribute('src', 'url_of_your_script')
    document.body.appendChild(insertScript)


text:
Q: How can I add properties to the mutation successful response I am new to graphql-spqr so I hope this is an easy question, however I couldn't find a solution for this, even after a long search.
Hint: In my app, I use the code-first/schema-last approach, which I like about the graphql-spqr, so there is no schema.graphqls loaded from a file.
My User.java starts with this
@Table(name = "users")
@Entity
@Setter
@Getter
@EntityListeners(AuditingEntityListener.class)
public class User {
  @Id
  @GraphQLQuery(name = "id", description = "A user's id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", nullable = false, updatable = false)
  public Long id;

  @GraphQLQuery(name = "firstName", description = "User's first name")
  @Column(name = "first_name")
  public String firstName;

  @GraphQLQuery(name = "lastName", description = "User's last name")
  @Column(name = "last_name")
  public String lastName;

  @GraphQLQuery(name = "email", description = "User's email")
  public String email;

  @GraphQLQuery(name = "uuid", description = "User's uuid")
  //@Type(type = "char")
  public String uuid;

  //@Type(type = "char")
  @Transient
  public Company company;

  @Column(name = "company")
  public Long companyId;

  @Transient
  public Role role;

  @Column(name = "role")
  public Long roleId;

  @Column(name = "pw")
  public String password;

  @GraphQLQuery(name = "terms", description = "User accepted terms")
  public Boolean terms;

  @Transient
  public String token;

  @CreatedDate
  public Instant created;

  public String getUuid() {
    return this.uuid;
  }

  public String getFirstName() {
    return this.firstName;
  }

  public String getLastName() {
    return this.lastName;
  }

  public String getEmail() {
    return this.email;
  }

  public String getPassword() {
    return this.password;
  }
}

A user is created by a mutation:
@GraphQLMutation(name = "createUser")
  public User createUser (
    @GraphQLArgument(name = "firstName") String firstName,
    @GraphQLArgument(name = "lastName") String lastName,
    @GraphQLArgument(name = "email") String email,
    @GraphQLArgument(name = "password") String password,
    @GraphQLArgument(name = "company") String company,
    @GraphQLArgument(name = "terms") Boolean terms) throws UserExistsException {

    ... some business logic

    ... and finally I use the JpaRepository<User, String> to save the user

    return userRepository.save(user);
 }

This is the query I am sending to the server

{"operationName":"CreateUser","variables":{"firstName":"Chris","lastName":"Rowing","email":"foo54@bar.com","password":"dada","company":"Test 5","terms":true,"source":"start","invitationId":null},"query":"mutation CreateUser($firstName: String!, $lastName: String!, $email: String!, $password: String!, $terms: Boolean!, $company: String) {\n  createUser(\n    firstName: $firstName\n    lastName: $lastName\n    email: $email\n    password: $password\n    terms: $terms\n    company: $company\n  ) {\n    id\n    __typename\n  }\n}\n"}

The new user gets saved in the DB, everything works fine, and in my Angular client I listen to the success event, and in the inspector there is the following output
{"data":{"createUser":{"id":4,"__typename":"User"}}}

My question
How can I customize the response? For example I need to respond also a JWT token, and maybe hide the id. I have not found a way to do this up to now and any help would be appreciated! Thanks!

A: For anyone who is experiencing the same newbie problem: This is how I solved it:
I added the token property to the GraphQL query, removed the id property, and added this to the UserService
// Attach a new field called token to the User GraphQL type
@GraphQLQuery
public String token(@GraphQLContext User user) {
  return authService.createToken(user.email, user.uuid);
}

It is possible to add external fields to the response without changing the original User.class by using @GraphQLContext


text:
Q: Best way to check if a character array is empty Which is the most reliable way to check if a character array is empty?
char text[50];

if(strlen(text) == 0) {}

or
if(text[0] == '\0') {}

or do i need to do
 memset(text, 0, sizeof(text));
 if(strlen(text) == 0) {}

Whats the most efficient way to go about this?

A: Given this code:
char text[50];
if(strlen(text) == 0) {}

Followed by a question about this code:
 memset(text, 0, sizeof(text));
 if(strlen(text) == 0) {}

I smell confusion.  Specifically, in this case:
char text[50];
if(strlen(text) == 0) {}

... the contents of text[] will be uninitialized and undefined.  Thus, strlen(text) will return an undefined result.
The easiest/fastest way to ensure that a C string is initialized to the empty string is to simply set the first byte to 0.
char text[50];
text[0] = 0;

From then, both strlen(text) and the very-fast-but-not-as-straightforward (text[0] == 0) tests will both detect the empty string.

A: This will work to find if a character array is empty. It probably is also the fastest.
if(text[0] == '\0') {}

This will also be fast if the text array is empty. If it contains characters it needs to count all the characters in it first.
if(strlen(text) == 0) {}

A: The second method would almost certainly be the fastest way to test whether a null-terminated string is empty, since it involves one read and one comparison.  There's certainly nothing wrong with this approach in this case, so you may as well use it.
The third method doesn't check whether a character array is empty; it ensures that a character array is empty.

A: The second one is fastest. Using strlen will be close if the string is indeed empty, but strlen will always iterate through every character of the string, so if it is not empty, it will do much more work than you need it to.
As James mentioned, the third option wipes the string out before checking, so the check will always succeed but it will be meaningless.

A: Depends on whether or not your array is holding a null-terminated string.  If so, then
if(text[0] == '\0') {}

should be sufficient.
Edit: Another method would be...
if (strcmp(text, "") == 0)

which is potentially less efficient but clearly expresses your intent.

A: if (text[0] == '\0')
{
    /* Code... */
}

Use this if you're coding for micro-controllers with little space on flash and/or RAM. You will waste a lot more flash using strlen than checking the first byte.
The above example is the fastest and less computation is required.

A: if (!*text) {}

The above dereferences the pointer 'text' and checks to see if it's zero.  alternatively:
if (*text == 0) {}


text:
Q: What to replace in Crystal Report Programmatically? I have a line of code to set the Report.PrintDate in VB6.How can we replace this line for CrystalDecisions.CrystalReports.Engine.ReportDocument ? In VB6 we have it is the inbuilt property for CRAXDRT.Report.
So can any once help me regarding this ?

A: if you want to show the current Date/Time of the printed report, you can use the built in Special Fields within the report designer . From your comment I understand you want to set that programatically. Then you need to create a Parameter and set it from code.

You can watch this DEMO to get to know how to create parameters. This Answer would show you how to pass the parameter from code.


text:
Q: python slicing string by pointing special character I have some strings that have been divided into 2 parts by - sign, for example:
s = 'Teh-Iran'

I want to cut the string to pick up the first parts only, for example the word Teh
The problem is that the length of first parts and the length of the second parts are not certain. So how can I slice them by pointing at - sign to use the first parts?

A: Go for the split method of str type:
>>> "Teh-Iran".split('-')
['Teh', 'Iran']
>>> "Teh-Iran".split('-')[0]
'Teh'
>>>


text:
Q: Excel Plotting two Date Ranges on the same Pivot Table I am trying to trend the occurrence of a system event in Excel. I've attached a screen shot showing the pretty simple data that I'm working with.
The spreadsheet lists the times of the event (Column A) for a two week period and I've used a ceiling formula to group those events into 15 minute increments (Column B).  Using a pivot table and chart, it's pretty simple to then take that data and graph the events into a line chart that shows the 15 minute increment time, and the count of the events in that 15 minute period.
Now I'd like to take subsets of that data and compare them. For example I'd like to compare Friday Saturday Sunday of last week Friday Saturday and Sunday of this week.  So far, the only way I found to achieve this is to create duplicate pivot tables (Columns E, F and H,I), filter each table by the days I want to compare (25, 26, and 27 in one table and 1, 2 and 3 in the second), and then visually compare them (the Two charts).
But what I'd really like to do is to combine both series into one chart as a stacked line graph.  I thought that would be pretty simple, but since the dates are so very dissimilar, I always wind up getting a single line or duplicate data, or totally off the wall results.
I've gotten kinda close by converting the row labels in to a custom DDD HH:MM format.  That lists the Dates as (For Oct 25th)

*

*Fri 00:15   11

*Fri 00:30   1

*Fri 00:45   4

*Fri 01:00   3

*Fri 01:15   6

*Etc.

And (For Nov 1st)

*

*Fri 00:15   7

*Fri 00:30   1

*Fri 00:45   2

*Fri 01:00   1

*Fri 01:30   2

*Etc

Now I have something I can join on (Friday 00:15, 00:30, 00:45, etc is in both charts)
But the problem is, the two series often don't have the same Labels.  For example the data for Nov 1 is missing 01:15,01:45 and 02:00 because no events occurred at those times.  Same problem for the Oct 25th's data which is also missing 02:00 in addition to all increments between 02:30 and 03:45.
I tried just manually inserting the missing times in both charts but that quickly became a very complex and error prone chore.
So the question is: Is there a way to get excel to automatically fill in the missing time slots or am I completely off base in the way I'm trying to do this?
OK.. that was two questions  :)
Thanks so much for your help!


text:
Q: Prove that $f$ either vanishes at all points or at no points Let $A \subseteq \mathbb{C}$ and assume $A$ is both open and connected. Let furthermore $(f_n)$ be a sequence of continuous functions on $A$ which converges uniformly to a holomorphic $f$ on all compact sets. Assume that $f_n$ never vanishes for any $n \in \mathbb{N}$.
I want to prove that $f$ either vanishes at all points or at no points.
My idea is assuming towards a contradiction that there exists $z, z' \in \mathbb{C}$ s.t. $f(z) = 0 $ and $f(z') \neq 0$. Then maybe i could somehow use Rouche's Theorem and perhaps the Maximus modulus principle to get some kind of contradiction of the boundary of some disc but I can't seem to make it work. Is it possible to do it this way? Or is there a better way (still using some Complex Analysis preferably)?


text:
Q: Can glog (c++) print line number in its stacktrace? glog (c++)'s failure signal handler can print stacktrace on segfault etc (see here). Can the stacktrace include line number as well?
Edit:
Even if I use LOG(FATAL), the stacktrace does not have line number.
*** Check failure stack trace: ***
    @     0x7f43546debd6  google::LogMessage::Fail()
    @     0x7f43546deb1a  google::LogMessage::SendToLog()
    @     0x7f43546de46b  google::LogMessage::Flush()
    @     0x7f43546e1530  google::LogMessageFatal::~LogMessageFatal()

I initializes glog as follows
  google::InstallFailureSignalHandler();
  google::InitGoogleLogging(argv[0]);
  gflags::ParseCommandLineFlags(&argc, &argv, /*remove_flags=*/true);

If you are seeing line numbers, what could I be missing? Thanks!

A: There is a fatal message before stack trace.
WARNING: Logging before InitGoogleLogging() is written to STDERR   // here
F1015 19:51:48.561210 15798 test.cc:36] []This is a test
*** Check failure stack trace: ***
Aborted (core dumped)


text:
Q: Displaying async data in angular 7 I am getting an object from server which in one field contains a html markup. So to make angular display it a used this piece of code.

With local data works perfectly. Although, with data from server, i used for the other fields the ? parameter like this {{o?.category}}.
But with the description field,i got this error,

ERROR TypeError: Cannot read property 'description' of undefined

So, what's the alternative for ? inside the byPassSecurityTrustHtml?

A: You are not using the elvis operator in your example, this:

Should be:


text:
Q: inserting multiple checkboxes names with codeigniter in to mysql I want to make a timetable with, Codeigniter
but I have a problem with looping.
My view
Class
`<input type="checkbox" name="class[]" value="1A" id="1a" /> 1A
<input type="checkbox" name="class[]" value="1B" id="1b" /> 1B
<input type="checkbox" name="class[]" value="1C" id="1c" /> 1C `

Hours
<input type="checkbox" name="hours[]" value="1" id="h1" /> hours 1
     <input type="checkbox" name="hours[]" value="2" id="h2" /> hours 2
    <input type="checkbox" name="hours[]" value="3" id="h3" /> hours 3
    <input type="checkbox" name="hours[]" value="4" id="h4" /> hours 4
    <input type="checkbox" name="hours[]" value="5" id="h5" /> hours 5
    <input type="checkbox" name="hours[]" value="6" id="h6" /> hours 6
Day
`<input type="checkbox" name="day[]" value="1" id="Monday" /> Monday
<input type="checkbox" name="day[]" value="2" id="Tuesday" /> Tuesday
<input type="checkbox" name="day[]" value="3" id="Wednesday" /> Wednesday
<input type="checkbox" name="day[]" value="4" id="Thursday" /> Thursday
<input type="checkbox" name="day[]" value="5" id="Friday" /> Friday
<input type="checkbox" name="day[]" value="6" id="Saturday" /> Saturday `

room
` A
<input type="checkbox" name="room[]" value="B" id="b" /> B
<input type="checkbox" name="room[]" value="C" id="c" /> C
<input type="checkbox" name="room[]" value="C" id="d" /> D `

my model
function add(){
    $day= $this->input->post('day');
    $hours= $this->input->post('hours');
    $class= $this->input->post('class');
    $room= $this->input->post('room');

    foreach ($hoursas $hr){
    $data = array('day'=>$day,'hours'=>$hr,'class'=>$class,'room'=>$room);
    $this->db->insert('t_jadual', $data);
    }
}

how do I loop $class,$room and $day?


text:
Q: Using write(), read() and a fifo to share data between processes in C I wrote this piece of code to show the basic working of how I would like to send some data (Strings) from the parent process to the child process. But I seem to have some problems. (I removed all error checking to make the code more readable)
When I run this piece of code I expect to see the two test strings to be displayed on the terminal, but I only see the first one.
When I uncomment the first "sleep(1)", then I see both strings displayed.
But when I uncomment only the second "sleep(1)", then I again only see the first string.
I suspect this problem has something to do with synchronization. That the strings get written to fast and the fifo write end closes before everything is read by the child process. That's why we see the correct output when we introduce a sleep between the two write() commands.
But what I don't understand is that we still get a faulty output when we only introduce a sleep after both write commands. Why can't the child read both strings even if they are both written before it can read one?
How can I solve this problem? Do I need some synchronization code, and if so how should I implement this. Because I won't write a "sleep(1)" after every write command.
And is the solution also viable for multiple processes that want to write to the same fifo? (but with still only one process that reads from the fifo)
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char const *argv[]) {
    mkfifo("test_fifo", 0666);
    pid_t pid = fork();

    if (pid == 0) {
        int fd = open("test_fifo", O_RDONLY);
        char data[400];
        int rc;
        do {
            rc = read(fd, data, 400);
            if (rc > 0) printf("Received data: %s\n", data);
        } while(rc > 0);
    }
    else {
        int fd = open("test_fifo", O_WRONLY);
        char * string1 = "This is the first test string";
        write(fd, string1, strlen(string1) + 1);
        //sleep(1);
        char * string2 = "This is the second test string";
        write(fd, string2, strlen(string2) + 1);
        //sleep(1);
        close(fd);
        wait(NULL);
    }
    return 0;
}

A: You are receiving both strings at the same time at the first call to read. Because %s prints up until a zero byte, the second string is just not displayed. The poor mans synchronization with sleep(1) allows child to "catch" the messages in two distinct read call.
read returns the count of bytes read. Use that number. Change the parent code to:
    ssize_t rc;
    do {
        rc = read(fd, data, 400);
        if (rc > 0) {
            printf("Received data: ");
            for (size_t i = 0; i < rc; ++i) {
                if (data[i] == '\0') {
                    printf("\\x00");
                    continue;
                }
                printf("%c", data[i]);
            }
            printf("\n");
        }
    } while(rc >= 0);

and it shows on my pc:
Received data: This is the first test string\x00This is the second test string\x00

Why can't the child read both strings even if they are both written before it can read one?

Well, the problem is not in reading, it's how you are displaying the data you read. (Still, reading could be improved, one should handle that pesky EAGAIN errno code).

How can I solve this problem?

If you want 1:1 relationship between read/write use a constant size packets or generally you have to know in advance how many bytes you want to read. Bytes written are "concatenated" together and lose structure. Or use pipe(3p) on which messages with size smaller then PIPE_BUF are guaranteed to be atomic. Or you could use POSIX message queue mq_receive/mq_send.
Or write a proper "deserializer", something that will buffer data and keep internal state and notify higher level only when a whole "message" was received, ie. detect when a zero byte was received in the stream of bytes and restore structure the the stream of bytes.


text:
Q: Json parsing in windows phone (C#) I am new to Windows Phone development.I want to parse some data using json parsing.After
googling i find a number of example but I am not able to understand properly.I have follow
a link
http://dotnetbyexample.blogspot.in/2012/01/json-deserialization-with-jsonnet.html
to do  json parsing But i am not able to show Storage ,Memory, ScreenSize in my List and my code is
    private void Load_Click(object sender, RoutedEventArgs e)
    {
        var w = new WebClient();
        Observable
          .FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
          .Subscribe(r =>
          {
              var deserialized =
                JsonConvert.DeserializeObject<List<RootObject>>(r.EventArgs.Result);
              PhoneList.ItemsSource = deserialized;
          });
        w.DownloadStringAsync(
          new Uri("http://www.schaikweb.net/dotnetbyexample/JSONPhones1.txt"));
    }

}

public class Specs
{
    public string Storage { get; set; }
    public string Memory { get; set; }
    public string Screensize { get; set; }
}

public class RootObject
{
    public string Brand { get; set; }
    public string Type { get; set; }
    public Specs Specs { get; set; }
}

}
Please Help me to solve this issue or any other sample for the same is also appreciated
Thanks

A: The code seems ok, so if you aren't running in to any errors there might be an issue with your UI code or UI to data coupling.
You need to post the UI code to get some help with this I suspect.


text:
Q: DynamoDB - problems using a local installation Am attempting to work with a local install of DynamoDb (per this). Ive opened the web UI (http://localhost:8000/shell) and created a few tables and can see them using the web UI.
If I try to view these same tables using either the cmd line or a simple java app I don't see them.
Cmd line: aws dynamodb list-tables --endpoint-url http://localhost:8000
Java:
AmazonDynamoDBClient client = new AmazonDynamoDBClient().withEndpoint("http://localhost:8000");

public void listMyTables() {
    TableCollection<ListTablesResult> tables = dynamoDB.listTables();
    Iterator<Table> iterator = tables.iterator();

    System.out.println("Listing table names");

    while (iterator.hasNext()) {
        Table table = iterator.next();
        System.out.println(table.getTableName());
    }
}

I've tried adding my credentials as follows:
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
        new ClasspathPropertiesFileCredentialsProvider("credentials")).withEndpoint("http://localhost:8000"));

To further confuse matters: if I create a table using the cmdline I can see it appear using the above cmdline but not via the WebUI or Java.
So: what glaringly obvious error am I making?

Addendum:
Im pretty sure all three methods are looking at the local db because if I stop it they all error out.

A: I think I figured this out. If you start the local db instance as follows:

java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

it works between the UI, cmd line and Java. Note the -sharedDb part of the cmd line. I believe that the local shell starts up in a "region" and unless you specify the region with your commands (or use the above param to negate regions) you'll run into what I saw above.


text:
Q: A super simple Multer question, nested file uploading I'm trying to do an image upload with Multer and Express. Doing just an image upload is going fine and everything works, the problem is, I want to send more than just one photo. Let me explain. I got the most basic form ever, not worth sharing. Then when submitting the form with JUST an image, the axios request looks like this:
async onSubmit() {
    const formData = new FormData();
    formData.append('file', this.person.personData.file)
    this.obj.file = formData

    try {
        await axios.post('/projects/new', this.obj.file);
        this.message = 'Uploaded';
    } catch (err) {
        console.log(err);
        this.message = 'Something went wrong'
    }
},

The post route in Express to receive the image looks like this:
personRoutes.post('/new', upload.single('file'), (req, res) => {
    console.log('BODY: ', req.body)
    console.log('REQ.FILE: ', req.file)

    const person = new Person({
        personData: {
            file: req.file.path
        }
    });
    person.save()
        .then(result => {
            console.log('YES', result)
            res.redirect('/projects')
        })
        .catch(err => {
            console.log('KUT', err)
        })
});

req.file is the upload.single('file') file. Req.body will hold the text fields, if there were any. Ez Pz, so far so good. Now, where things get a bit sketchy is, what if I wanted to upload more than just one photo? So my obj object would not only hold a file property but a few others aswell. Currently I am directly sending the formData file with
await axios.post('/projects/new', this.obj.file);

But if my obj contained more than just a file, I would have to to this:
await axios.post('/projects/new', this.obj);

But what in the world should my Express post route look like? Because req.file will now (as far as I know) forever be undefined because file is not defined inside req object. It is defined in req.body object. Accessing the file as req.obj.file won't do anything. Any help would be very much appreciated. I don't even know if it is possible. And if not, what other options do I have?
Thanks in advance!

A: upload.array('file') should work. any number of files will be received.
here is an example:
multer code:
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads')
    },
    filename: (req, file, cb) => {
        cb(null, "image"+Date.now()+file.originalname);
    }
});
const fileFilter = (req,file,cb)=>{
  if(file.mimetype==="image/jpeg" || file.mimetype==="image/png"){
      cb(null, true);
  }else{
    cb(new Error("File type is not acceptable"),false);
  }
}

const uploadImages = multer({storage:storage,
  limits:{
      fileSize: 1024*1024*10
    },
    fileFilter:fileFilter}).array("shopImage");

app.post code:
app.post("/shop", function(req,res){
  uploadImages(req,res,function(err){
    if(err){
      console.log(err);
      res.status(400).json({message:err.message});
    }else{
      console.log(req.files);
      console.log(req.body);
....
    }
  });
....
})


text:
Q: How to create a SQLite3 DB in Android Via JNI (C ? C++) I have been trying to create a new SQLite3 db (SQLite - C/C++) in Android via JNI but the db file doesn't get created.
Tutorialspoint : Connect To Database
void createDb() {
    sqlite3 *db;
    int rc;

    rc = sqlite3_open("/storage/emulated/0/Download/sqlite_lite.db", &db);

    if (rc) {
        __android_log_print(ANDROID_LOG_ERROR, "MyApp", "Can't open database: %s\n", sqlite3_errmsg(db));
    } else {
        __android_log_print(ANDROID_LOG_ERROR, "MyApp", "Opened database successfully\n");
    }
}

I get an erro : Could not create db
I have the Permissions enabled (manifest) :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

What am I missing? I have the above wired up via JNI :
extern "C"
JNIEXPORT void JNICALL
Java_com_initDb(JNIEnv *env, jobject instance) {
    createDb();
}

public class SQLiteDB {

    static {
        System.loadLibrary("sqlite-db");
    }

    public native void initDb();

}

How can I get my app to create the database file?
Thank you all in advance.

UPDATE :
I'm working from React Native. This is how I'm getting my Runtime Permissions :
const requestCameraPermission = () => {
  try {
    PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.ACCESS_MEDIA_LOCATION,
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
    ]).then(result => {
      if (
        result['android.permission.ACCESS_MEDIA_LOCATION'] &&
        result['android.permission.READ_EXTERNAL_STORAGE'] &&
        result['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted'
      ) {
        console.log('SUCCESS! Permissions Granted!');
      }
    });
  } catch (err) {
    console.warn(err);
  }
};

However, there doesn't seem to be READ_INTERNAL_STORAGE available in React Native.


text:
Q: Ruby on Rails namespace issue with iCalendar i'm developing a calendar webapp for my company using ruby 1.8.7 and
rails 2.3.8.  naturally there are RoR models named "Calendar" and "Event".
in order to send calendar events to other apps (microsoft outlook &
lotus notes) i'm integrating with the iCalendar standard & ruby
library.  http://icalendar.rubyforge.org/
but this library contains classes called "Calendar" and
"Event"
now my app is getting lotta errors like this when it tries to use
activerecord find - @calendar = Calendar.find(id) :
NoMethodError (undefined method find' for **Icalendar::Calendar:Class**):
 app/controllers/foos_controller.rb:184:insendEmailDialogForm'
 C:/Ruby/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
is there some way to do:
@calendar = ActiveRecord::Base.Calendar.find(id) ??
  or

@calendar = appname.Calendar.find(id)
  or

@calendar =  this.Calendar.find(id)
lazily trying to avoid using a module to specify a namespace or to rename my
models.

A: I'm thinking you have an include Icalendar somewhere.  Try pulling that out & making your calls to that library using Icalendar::Calendar.new(...).  This should take care of the namespace conflicts.


text:
Q: Not able to update multiple rows in Oracle at a time I am trying to execute an update query in a table where I am trying to insert foreign key for some table,
Query is:
update TABLE_1 set TABLE_2_ID = (select TABLE_2_ID from TABLE_2)

Getting Exception:

caused by : "ORA-01427: single-row subquery returns more than one row

I have googled the problem I know the problem is I have multiple result rows from select TABLE_2_ID from TABLE_2 which I am trying to update in a single row, but I have not been able to identify the result.

A: Add a line of code in "update TABLE_1 set TABLE_2_ID = (select TABLE_2_ID from TABLE_2 where XXXXX)" to make sure (select TABLE_2_ID from TABLE_2 where XXXXX) return only one result

or like this

update  TABLE_1
  set (TABLE_1.a2,TABLE_1.a3) =(select TABLE_2.b2,TABLE_2.b3
  from  TABLE_2
  where TABLE_2.b1= TABLE_1.a1 and TABLE_1.a3=xxx
  )
where exists
(select 'X' from TABLE_2 where TABLE_2.b1=TABLE_1.a1 and TABLE_1.a3=xxx);
commit;


text:
Q: relation between tables Laravel I have 3 tables one for courses and second table for classes and the other table for categories which categories can have multiple classes. so I want to show list of courses with classe_name and category name.
I make pivot table between classes and categories which also contain course name, but I can't show catgory name from table categories and I don't know if this is the correct way
//method to show courses
public function index()
{

   $categories=Course_category::all();
   return view('teacher.courses')->with('categories',$categories);
}

blade
     @foreach ($categories->classe as $item)
                    {{$item->category_name}}
     @endforeach

categorie model
     protected $table = 'categories';
            protected $fillable =['id','category_name','categorie_image'];

            /**
             * The roles that belong to the Course_category
             *
             * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
             */

            public function classe(){

                return $this -> belongsToMany('App\Classe','classe_categorie','categorie_id','classe_id');
            }

classe model
 protected $table = 'classes';
    protected $fillable=['id','classe_name','classe_image'];
    public function course_categorie() {

        return $this -> belongsToMany('App\Course_category','classe_categorie','classe_id','categorie_id');
    }

A: You should loop through classes, not categories:
 @foreach ($categories->classe as $item)
    {{$item->category_name}}
 @endforeach

It should be
 @foreach ($categories as $item)
    {{$item->classe->classe_name}}
    {{$item->category_name}}
 @endforeach

As you want to show classes, why don't you collect all Classes in the controller and start from there? Unless you want to group by categories, which is easily done with eloquent.

A: thank you for your help i found the solution
$categories=Course_category::with('classe')->get();

and i use loop inside loop for the collection
@foreach ($categories as $item)
            {{-- {{$item->course_category->category_name}} --}}
              @foreach ($item->classe as $cat)
                  {{$cat->course_name}}
                  {{$cat->classe_name}}
              @endforeach
            @endforeach


text:
Q: How to get Google Doc using URL or ID in Apps Script? How to get Google Doc using URL or ID in Apps Script?
I'm working on a chat app running on Apps Script that stores data on a Google Doc and shows the data on the interface. However, I didn't link it to a Doc, and I want to publish it as a web app. I want to know how I can get a Doc with a URL or an ID. Does anyone know how to do this?


text:
Q: insert statement using current date column value I'm getting the following error while running this statement. I need to insert date functions in the columns. Any idea on this will be really helpful.
Error message:

Error - ORA-20000: ORA-01843: not a valid month at pos 504 : TO_CHAR((LAST_DAY(ADD_MONTHS(sysdate, -1))),'DD/MM/YYYY')

Data Type:
data type for ATT3 is DATE(7),
ATT1 and ATT2 is VARCHAR2(400)
Query:
insert into ABC (X, Y, Z, ATT1, ATT2, ATT3)
VALUES ('G', 'H', 'I',
        TO_CHAR(LAST_DAY(ADD_MONTHS(sysdate, -1)),'Mon DD YYYY HH:MI AM'),
        TO_CHAR(sysdate, 'Mon D YYYY HH:MI AM'),
        TO_CHAR((LAST_DAY(ADD_MONTHS(sysdate, -1))),'DD/MM/YYYY'));

A: TO_CHAR(sysdate, 'Mon D YYYY HH:MI AM') will give incorrect result. You need to change it to TO_CHAR(sysdate, 'Mon DD YYYY HH:MI AM').
Please paste the structure of the table with the data types.


text:
Q: Condition not satisfied when comparing empty Strings in Spock I'm trying to check that 2 strings are equal but I'm hitting. Both Strings are empty:
Condition not satisfied:

versionTagPrefix == ""
|                |
""               false
                 2 differences (0% similarity)
                 ("")
                 (--)

I've also tried equals:
Condition not satisfied:

"".equals(versionTagPrefix)
   |      |
   false  ""

Versions:
compile 'org.codehaus.groovy:groovy-all:2.0.1'
testCompile "org.spockframework:spock-core:0.7-groovy-2.0"

A: As far as i know, groovy has many implementations of Strings.
When you see messages in output/error stream you are probably looking at value of toString() instead of actual content of object.
To go in deep and debug, use .properties attribute on objects.
For example :
1 org.codehaus.groovy.runtime.GStringImpl
groovy:000> i=10; s1="$i"; "type=${s1.class}\n
                            content=${s1.properties}\n
                            out=${s1.toString()}"
===> type=class org.codehaus.groovy.runtime.GStringImpl
     content=[values:[10],
              class:class org.codehaus.groovy.runtime.GStringImpl,
              bytes:[49, 48], strings:[, ], valueCount:1]
     out=10

2. java.lang.String
groovy:000>s2="10"; "type=${s2.class}\n
                        contents=${s2.properties}\n
                        out=${s2.toString()}"
===> type=class java.lang.String
     contents=[class:class java.lang.String, bytes:[49, 48], empty:false]
     out=10

And can be many implementations....

Though in this case s1 == s2, you might have a situation where s1 != s2 but s1.toString() == s2.toString()
assert versionTagPrefix?.toString() == ""


text:
Q: Why does this NodeJS code return empty response object? This is the code:
router.post("/form", async (req, res) => {
  try {
    let { name, email, password } = req.body;
    let user = await User.create({
      name,
      email,
      password,
    });

    if (!user) return res.status(501).send("Something went wrong");
    let token = await user.getSignedToken();
    console.log(token); //Server logs this

user.emailToken = await user.verifyEmail();// This property is not being added in the saved mongodb document. It should, but again idk why it's not

    await user.save({ validateBeforeSave: false });
    console.log(user); // Server doesn't log this
    const options = {
      expires: new Date(
        Date.now() + process.env.JWT_COOKIE_EXPIRE * 24 * 60 * 60 * 1000
      ),
    };
    console.log(options); // Server doesn't log this
    res.cookie("token", token, options);
    res.send("Check email for activation");
  } catch (ex) {
    res.send(ex);
  }
});

Below is the verifyEmail method (in userSchema.. I'm using mongoose):
userSchema.methods.verifyEmail = async function () {
  let emailToken = this._id + crypto.randomBytes(10).toString("hex");
  let emailTokenHashed = await crypto
    .createHash("sha256")
    .update(passwordToken)
    .digest("hex");
  this.emailToken = emailTokenHashed;

  return emailToken;
};

Now, it should send "Check email for activation", right? But, it's sending an empty response object. Also, if you see in the code, the server is logging only one console.log (i.e. the first console.log). But, it is sending a cookie (I checked via postman). So, what's the issue here?

A: This code sends res.send("Check email for activation"); or res.send(ex);.  Since you say that:
console.log(options); // Server doesn't log this

then one of your await statements must be hitting a rejected promise and sending you to the catch.  Add console.log(ex) right before res.send(ex) to see what the error is so you have this:
} catch (ex) {
    console.log("got error", ex);
    res.send(ex);
}

And, then see what you get in the log.
In general you never want to send an error object directly because most of its properties are non-enumerable so they won't get sent as JSON and that may make the error object completely empty when it gets converted to JSON and thus isn't useful to the client at all.  Instead, log the error on your server and send a 500 status:
res.sendStatus(500);

Or, if you want to send an error object construct your own error object with regular, enumerable properties and send that.
Anyway, once you add the console.log(ex) to your server, it should tell you what the actual rejected promise is and that will show you what's going wrong with the request.  ALWAYS log errors on the server to help you see and solve problems like this.


text:
Q: C# Matrix gives weird mouse coordinates I am writing a custom control which draws polygons.
I use matrix calculations to scale and shear the polygons so that they fit the control.
I need to know if the mouse has been clicked inside one of the polygons, so I am using ray casting.
This all seems to work fine individually, however I am now encountering an issue with retrieving the mouse coordinates relative to the display matrix im using.
I use the following code:
// takes the graphics matrix used to draw the polygons
Matrix mx = currentMatrixTransform;

// inverts it
mx.Invert();

// mouse position
Point[] pa = new Point[] { new Point(e.X, e.Y) };

// uses it to transform the current mouse position
mx.TransformPoints(pa);

return pa[0];

now this works for every other set of coordinates, by that I mean that one pair of mouse coordinates appears to give the correct values as if it has been through the matrix, but the one beside it gives a value as if it has not been through the matrix, below is an output of the mouse values received when moving down the control.

{X=51,Y=75}
      {X=167,Y=251}
      {X=52,Y=77}
      {X=166,Y=254}
      {X=52,Y=78}
      {X=166,Y=258}
      {X=52,Y=79}
      {X=166,Y=261}
      {X=52,Y=80}
      {X=165,Y=265}
      {X=52,Y=81}
      {X=165,Y=268}

if it helps the matrix used to draw the polygons is
Matrix trans = new Matrix();
trans.Scale(scaleWidth, scaleHeight);
trans.Shear(italicFactor, 0.0F, MatrixOrder.Append);
trans.Translate(offsetX, offsetY, MatrixOrder.Append);

e.Graphics.Transform = trans;
currentMatrixTransform = e.Graphics.Transform;

Thanks in advance

A: You are inverting your matrix each time you call it.
Matrix is a class, meaning that by performing Invert() on mx, you are also performing it on currentMatrixTransform.
You can either copy the matrix using Clone() and then invert the clone,
or you can perform Invert() once again after you've transformed the point pa.
A second invert example:
// takes the graphics matrix used to draw the polygons
Matrix mx = currentMatrixTransform;

// inverts it
mx.Invert();

// mouse position
Point[] pa = new Point[] { new Point(e.X, e.Y) };

// uses it to transform the current mouse position
mx.TransformPoints(pa);

// inverts it back
max.Invert();

return pa[0];

A clone example:
// takes the graphics matrix used to draw the polygons
Matrix mx = currentMatrixTransform.Clone();

// inverts it
mx.Invert();

// mouse position
Point[] pa = new Point[] { new Point(e.X, e.Y) };

// uses it to transform the current mouse position
mx.TransformPoints(pa);

return pa[0];


text:
Q: Collecting the Log Problem I have been having tremendous success with my students due to the following idea:
expandLog = {Log[x_] + Log[y_] :> Log[x y], n_ Log[x_] :> Log[x^n]}

collectLog = {Log[x_ y_] :> Log[x] + Log[y], Log[x_^n_] :> n Log[x]}

Written on Simplify expressions with Log by RunnyKine. Extremely easy to understand and to explain to the students. However, I've finally encountered a difficulty:
This worked:

But this didn't:

I tried a number of different things, like using the Algebraic Manipulation Palette, highlighting the interior, but none worked.
Any suggestions?

A: You just need to write a general rule that takes a base like this:
logbaserule = {Log[k_, x_] + Log[k_, y_] :> Log[k, x y], n_ Log[k_, x_] :> Log[k, x^n]};

revlogbaserule = {Log[k_, x_ y_] :> Log[k, x] + Log[k, y], Log[k_, x_^n_] :> n Log[k, x]};

Now you can apply to your question:
Log[2, x + Sqrt[x^2 - 1]] + Log[2, x - Sqrt[x^2 - 1]] //. logbaserule // Simplify

0

You can also use FullSimplify with a transformation function to go directly to the final result:
tf[x_] := x /. logbaserule

FullSimplify[Log[2, x + Sqrt[x^2 - 1]] + Log[2, x - Sqrt[x^2 - 1]],
                 TransformationFunctions -> {Automatic, tf}]

0


text:
Q: Console displaying information of 4 objects when there is only 1 object in my array I have the following code in angularjs:
TimeSlotsModel.all()
            .then(function (result) {
                vm.data = result.data.data;

                var events = [];

                 angular.forEach(vm.data, function(value,key) {

                    var eventName = value.name;
                    var startDate = new Date(value.startDate);
                    var endDate = new Date(value.endDate);

                    var selectedStartingTime =new Date(value.startTime * 1000 );
                    var selectedEndingTime = new Date(value.endTime * 1000);

                    //timing is not right, needs fixing
                    startTime = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),selectedStartingTime.getHours(), selectedStartingTime.getUTCMinutes());
                    endTime = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),selectedEndingTime.getUTCHours(), selectedEndingTime.getUTCMinutes());
                    // console.log(startTime);
                    events.push({
                        title: 'Event -' + eventName,
                        startTime: startTime,
                        endTime: endTime,
                        allDay: false

                    });

            console.log(eventName);
            console.log(events);
            // console.log(value);

             //value is the object!!
            })
             return events;
             $scope.$broadcast('eventSourceChanged',$scope.eventSource);

            })

         }

Everytime the forEach loop runs through my array of objects , vm.data, the console prints this:

My questions are :
1) Why are the details of the 4 objects being printed? Does it mean that for every object in the array it contains 4 other objects?
2) Is each object pushed to the events[ ] properly?
3) If the answer to question 2 is no, what should I do to resolve it?
EDIT: Updated code to using promise to return events array:
    //Calendar Controller
  .controller('CalendarCtrl', function ($scope,TimeSlotsModel,$rootScope,$q) {
    var vm = this;

    function goToBackand() {
        window.location = 'http://docs.backand.com';
    }

    function getAll() {
        TimeSlotsModel.all()
            .then(function (result) {
                vm.data = result.data.data;
            });
    }

    function clearData(){
        vm.data = null;
    }

    function create(object) {
        TimeSlotsModel.create(object)
            .then(function (result) {
                cancelCreate();
                getAll();
            });
    }

    function update(object) {
        TimeSlotsModel.update(object.id, object)
            .then(function (result) {
                cancelEditing();
                getAll();
            });
    }

    function deleteObject(id) {
        TimeSlotsModel.delete(id)
            .then(function (result) {
                cancelEditing();
                getAll();
            });
    }

    function initCreateForm() {
        vm.newObject = {name: '', description: ''};
    }

    function setEdited(object) {
        vm.edited = angular.copy(object);
        vm.isEditing = true;
    }

    function isCurrent(id) {
        return vm.edited !== null && vm.edited.id === id;
    }

    function cancelEditing() {
        vm.edited = null;
        vm.isEditing = false;
    }

    function cancelCreate() {
        initCreateForm();
        vm.isCreating = false;
    }

    // initialising the various methods
    vm.objects = [];
    vm.edited = null;
    vm.isEditing = false;
    vm.isCreating = false;
    vm.getAll = getAll;
    vm.create = create;
    vm.update = update;
    vm.delete = deleteObject;
    vm.setEdited = setEdited;
    vm.isCurrent = isCurrent;
    vm.cancelEditing = cancelEditing;
    vm.cancelCreate = cancelCreate;
    vm.goToBackand = goToBackand;
    vm.isAuthorized = false;

    //rootScope refers to the universal scope, .$on is a receiver for the
    //message 'authorized'
    $rootScope.$on('authorized', function () {
        vm.isAuthorized = true;
        getAll();
    });

    $rootScope.$on('logout', function () {
        clearData();
    });

    if(!vm.isAuthorized){
        $rootScope.$broadcast('logout');
    }

    initCreateForm();
    getAll();

    $scope.calendar = {};
    $scope.changeMode = function (mode) {
        $scope.calendar.mode = mode;
    };

    $scope.loadEvents = function () {
        $scope.calendar.eventSource = getEvents();
        $scope.$broadcast('eventSourceChanged',$scope.eventSource);

    };

    $scope.onEventSelected = function (event) {
        console.log('Event selected:' + event.startTime + '-' + event.endTime + ',' + event.title);
    };

    $scope.onViewTitleChanged = function (title) {
        $scope.viewTitle = title;
    };

    $scope.today = function () {
        $scope.calendar.currentDate = new Date();
    };

    $scope.isToday = function () {
        var today = new Date(),
            currentCalendarDate = new Date($scope.calendar.currentDate);

        today.setHours(0, 0, 0, 0);
        currentCalendarDate.setHours(0, 0, 0, 0);
        return today.getTime() === currentCalendarDate.getTime();
    };

    $scope.onTimeSelected = function (selectedTime) {
        console.log('Selected time: ' + selectedTime);
    };

    function getEvents(object){

      var deferred = $q.defer();

        TimeSlotsModel.all()
            .then(function (result) {
                vm.data = result.data.data;

                var events = [];

                 angular.forEach(vm.data, function(value,key) {

                    var eventName = value.name;
                    var startDate = new Date(value.startDate);
                    var endDate = new Date(value.endDate);

                    var selectedStartingTime = new Date(value.startTime * 1000 );
                    var selectedEndingTime = new Date(value.endTime * 1000);

                    //timing is not right, needs fixing
                    startTime = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),selectedStartingTime.getHours(), selectedStartingTime.getUTCMinutes());
                    endTime = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),selectedEndingTime.getUTCHours(), selectedEndingTime.getUTCMinutes());
                    // console.log(startTime);
                    events.push({
                        title: 'Event -' + eventName,
                        startTime: startTime,
                        endTime: endTime,
                        allDay: false

                    });
            // console.log(eventName);
            // console.log(events);
            // console.log(value);
            // console.log(key);
            // console.log(value);

             //value is the object!!
            })

            deferred.resolve(events);

            // return events;

            })
            return deferred.promise;
            console.log(deferred.promise);

         }

A: [!Removed old answer]
I believe James is right here the console might be the culprit, I just reproduced the same behaviour.


text:
Q: centering a video and a input box using flexbox I have a bit of a problem horizontally centering my video, input box and button in the center of the page. I've seen a few answers that say that I don't need flexbox and I've actually attempted to set my margin to auto(to center the content in the middle of the viewport)  to no avail. When I tried to inspect the code using chrome developer tools, It showed that my video, content, and form divs are taking up 100% of the width of the viewport, so it seems like that's the reason why I can't center it. Of course, I could be wrong. I'm stumped. Any help you guys give will be insanely useful right now. If this isn't clear let me know. This is what I have so far.
Thanks,
Anna

Want to read as fast as me? Follow the instructions below...

 <form>
<input type "text" placeholder="Tell us more about what books you
like.">
<form>

<button type="submit" name="button">submit</button>
Anna Gibson @ 2018

A: Okay, so this is what I did. I made it so that the 'content div' encompasses the video, input box, button and footer, and text-aligned them all to 'center'
.
Here's an example of my code below:
HTML:

Want to read as fast as me? Follow the instructions below...

      <form>
    <input type "text" placeholder="Tell us more about what books you like.">
    <form>
     <button type="submit" name="button">submit</button>

     Anna Gibson @ 2018

CSS:
.content {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

form {
  width: 200px;
  margin: 0 auto;
}

input{
  margin: auto;
  width: 200px;
  height: 150px;
  margin-top: 20px;
  border: 2px solid black;
}

button {
  margin-top: 40px;
  font-size: 18px;
  padding: 10px;
  text-align: center;
  background-color: #7a420a;
  color: white;
  margin: auto;
}


text:
Q: Print image with Chrome using command line switches / startup arguments Is there a way to open an image url with Chrome and print that image on start up using command line switches (start up arguments).
It can be headless or non headless. Printing to the default printer is fine as well.
This appears to be a complete list of chrome command line switches, but I'm not seeing anything that does quite what I'd like it to, although there's around 1,300 options so I may be missing something.

A: I've found a goofy work around that works for my specific situation. I am using C#, so this answer is C# specific, although you could probably apply the idea to most languages.
I start up chrome in --kiosk, --kiosk-printing mode, which disables print dialog. I then wait for chrome to start up. I then send the  CTRL + P keys. The full method looks like this.
public void printImageUrlWithChrome(string url)
{
    using (var process = new Process())
    {
        // Start Chrome in kiosk with kiosk printing (no printing confirmation window)
        process.StartInfo.FileName = Properties.Settings.Default.googleChrome;
        process.StartInfo.Arguments = url + " --kiosk --kiosk-printing";
        process.Start();

        // Wait for Kiosk to load
        int millisecondWaitForChrome = 1000;
        System.Threading.Thread.Sleep(millisecondWaitForChrome)

        // Send CTRL + p
        SendKeys.Send("^(p)");
    }
}

Would still prefer a less goofy solution, preferably something with command switches only.


text:
Q: An Question related to calculating $H^4(K(\mathbb{Z}/2,2))$ This is an assignment question with $3$ steps as follows:

$1.$ Prove that $H^2(K(\mathbb{Z},2);\mathbb{Z}/2)\cong \mathbb{Z}/2.$ Use this generator to obtain a map $K(\mathbb{Z},2)\rightarrow K(\mathbb{Z}/2,2)$. Prove that the homotopy fibre of the map is $\simeq$ $K(\mathbb{Z}/2)$.
$2.$ In the above fibration $\big(K(\mathbb{Z},2)\xrightarrow{f}{} K(\mathbb{Z},2)\rightarrow K(\mathbb{Z}/2,2)\big),$ prove that we get an induced map $q:Cone (f)\rightarrow K(\mathbb{Z}/2,2).$ Prove that $q_*$ is surjective on homotopy groups.
$3.$ Prove that $q$ is an $4$-equivalence. Use this to deduce that $H^4(K(\mathbb{Z}/2,2))\cong\mathbb{Z}/2$.

I have solved the first two parts of the question but I am completely clueless about the last part. I don't know how to calculate the homotopy groups of $Cone(f)$, I guess there must be a way around it. Any help is appreciated.


text:
Q: AWS::CloudFormation::Init not executing commands in metadata This is my template with a test command in the metadata. I can't figure out why the command doesn't get executed. It's supposed to save a string to a file in /tmp.
The machine is Ubuntu 16.04 with cloud-init installed. In UserData I install the helper scripts and execute cfn-init.
Thanks for your help.
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Metadata": {
    "AWS::CloudFormation::Designer": {
      "2af5b799-f6bf-7f20-a6eb-943274f18373": {
        "size": {
          "width": 60,
          "height": 60
        },
        "position": {
          "x": 326,
          "y": 118
        },
        "z": 0,
        "embeds": []
      }
    }
  },
  "Resources": {
    "EC2I3WADD": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "ImageId": "ami-c60b90d1",
        "KeyName": "CF-KEY",
        "InstanceType": "t2.micro",
        "UserData": {
          "Fn::Base64": {
            "Fn::Join": [
              "",
              [
                "#!/bin/bash -xe\n",
                "apt-get -y install python-setuptools\n",
                "mkdir aws-cfn-bootstrap-latest\n",
                "curl https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz | tar xz -C aws-cfn-bootstrap-latest --strip-components 1\n",
                "easy_install aws-cfn-bootstrap-latest\n",
                "/usr/local/bin/cfn-init --stack ",
                {
                  "Ref": "AWS::StackName"
                },
                " --resource WebServer",
                " --region ",
                {
                  "Ref": "AWS::Region"
                },
                "\n"
              ]
            ]
          }
        }
      },
      "Metadata": {
        "AWS::CloudFormation::Designer": {
          "id": "2af5b799-f6bf-7f20-a6eb-943274f18373"
        },
        "AWS::CloudFormation::Init": {
          "config": {
            "commands": {
              "test": {
                "command": "echo \"$MAGIC\" > /tmp/test.txt",
                "env": {
                  "MAGIC": "I come from the environment!"
                }
              }
            }
          }
        }
      }
    }
  }
}

A: The issue is likely being cause by an incorrect --resource argument being passed to the cfn-init command within your UserData.  This argument should match the logical resource name of the resource containing the MetaData, in your case EC2I3WADD.
"/usr/local/bin/cfn-init --stack ", { "Ref": "AWS::StackName" }, " --resource EC2I3WADD", " --region ", { "Ref": "AWS::Region" }

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-init.html


text:
Q: How to install MySQL GUI Tools in 12.04+ versions? I want to install the MySQL GUI Tools in 12.04 and future version because frankly the way workbench works is not even close to how friendly the GUI tools were, specially for simple stuff like doing a quick SELECT of something or selecting a table. I like using MySQL Administrator and MySQL Query Browser. The way they work is much more intuitive than Workbench. How can I install them in 12.04 and newer versions?

A: *

*I tried to compile without success because many bugs to fix :(

*I tried to convert .rpm package with alien, its convert and install well but doesn't work :(

*go to this page and download this packed : see UPDATE
32 bits
Generic x86 Linux TAR (bundled dependencies)         5.0r12
mysql-gui-tools-5.0r12-linux-i386.tar.gz

64 bits
Generic x86/64 Linux TAR (bundled dependencies)      5.0r12
mysql-gui-tools-5.0r12-linux-x86_64.tar.gz

*extract the tar.gz with nautilus doble-click :

*

*Open mysql-gui-tools-5.0 with nautilus an you will see :

*

*The first time open a terminal an execute ./mysql-administrator

if you see one error like that just execute ./mysql-administrator --update-paths

*

*for second time an more just execute via nautilus

and voala! happy rocking...
UPDATE 23/02/2013
MYSQL Announcement the EOL for the MySQL GUI Tools Bundle (Administrator, Query Browser, Migration Toolkit), please use MySQL Workbench has replaced the GUI Tools Bundle instead, and you can't download from the MYSQL web page but I found another page where you can find it:

*

*MySQLGUITools

A: A better solution is in this link. Where are mysql-admin and query-browser?
It's just a question of running this: sudo apt-get install mysql-workbench
The explanation for this new name "workbench" is in the link above
HTH

A: This is for 12.04+ users:
Since MYSQL has taken the link down, the only quick place I found the compressed MySQL GUI Tools was here:
http://mysql.ntu.edu.tw/Downloads/MySQLGUITools/mysql-gui-tools-5.0r14.tar.gz
So download that, decompress and follow the steps mentioned by hhlp here. Note that you need to compile it yourself. There is an autogen.sh file in both the Admin and Query folders. Run it and it will tell you what else you need to have it working.

A: See http://www.tolaris.com/2012/05/16/added-to-precise-repository-handbrake-mysql-query-browser/
While there are many possible paths to install (depending on your setup),  in more recent versions of Ubuntu (12+) you may manually add the following sources to /etc/apt/sources.list:
deb http://www.tolaris.com/apt/ precise main
deb-src http://www.tolaris.com/apt/ precise main

Then:

sudo apt-get update
sudo apt-get install mysql-gui-tools

(If your version of Ubuntu has been upgraded,  you may need to update *.archive.ubuntu.org sources to your current release,  as well-- for instance,  to 'saucy').
This seems the only viable path to installing the GUI tools at this point,  as all other sources are offline.

A: MYSQL Announcement the EOL for the MySQL GUI Tools Bundle (Administrator, Query Browser, Migration Toolkit), please use MySQL Workbench has replaced the GUI Tools Bundle instead, and you can't download from the MYSQL web page but I found another page where you can find it:

A: Run these commands in the Terminal:
aptitude search mysql-query-browser mysql-admin mysql-workbench
aptitude show tora


text:
Q: Do you need a subject in a sentence if it is implied from the previous sentence? These two sentences sound good to me in my head, but the second sentence isn't an independent clause. In my mind, the subject of the second sentence is implicitly taken from the previous sentence. Is this grammatically correct, or would I need a different mark of punctuation to pull this off?

Collective nouns can either be singular or plural. Plural when
  thinking of individuals in the group, singular otherwise.

A: It would be better to link them together with a colon:

Collective nouns can either be singular or plural: plural when thinking of individuals in the group, singular otherwise.

You might want to rearrange the sentence so that the word plural does not immediately follow itself.
A colon is useful here because the first half of the sentence sets things up (acts as an introduction) for the second half (which really contains the payload of the sentence). The Oxford Manual of Style has this to say about the colon (although this is only one of its uses):

The colon points forward: from a premise to a conclusion, from a cause to an effect, from an introduction to a main point; from a general statement to an example. It fulfils the same function as words such as namely, that is, as, for example, for instance, because, as follows, and therefore:

*

*There is something I must say: you are standing on my toes.

*It is available in two colours: pink and blue.

*French cooking is the restaurant's speciality: the suprêmes de volaille Jeanette was superb.

*She has but one hobby: chocolate.

The Oxford Manual of Style, 2002


text:
Q: Compostion of tempered distribution and linear map. While solving a particular problem about composition of tempered distributions and an affine transformation, I ended up having to prove the following for $u\in\mathscr{S}'$ and a linear transformation $L:\mathbb{R}^d\rightarrow \mathbb{R}^d$: $$u(\hat{\phi}\circ L^{-1}) = |\det L| u(\widehat{\phi\circ L^t)}$$
But I am stuck from here.

A: Assume that $|\det(L)| \neq 0$, then $L\mathbb{R}^n=\mathbb{R}^n$. Let $\phi \in \mathscr{S}$ and define $z(x)=L^tx$. Use the transformation rule to obtain
$$
\widehat{(\phi \circ L^t)}(k)=\int_{\mathbb{R}^n} {e^{-ik \cdot x}\phi(L^tx)}dx
= \frac{1}{|\det T|}\int_{\mathbb{R}^n} {e^{-ik \cdot L^{-t}z(x)}\phi(z(x)) |\det T|} dx
$$
$$
= \frac{1}{|\det T|}\int_{\mathbb{R}^n} {e^{-ik \cdot L^{-t}z}\phi(z)} dx
= \frac{1}{|\det T|}\int_{\mathbb{R}^n} {e^{-iL^{-1}k \cdot z}\phi(z)} dx
= \frac{1}{|\det T|}\hat{\phi}(L^{-1}k)
$$
Since $u \in \mathscr{S}'$ is linear
$$
u(\hat{\phi}\circ L^{-1}) = |\det L|u(\widehat{\phi\circ L^t)}
$$
which is the stement.


text:
Q: How to count proportional distribution of given numbers? I am trying to figure out how to count proportional distribution of given numbers - for example:
Number A: 5
Number B: 5
Number C: 5

In this case it means that the proportional distribution of each number is 33%.
But what if:
Number A: 17
Number B: 8
Number C: 59

I am trying to come up with a versatile formula (with rounding on zero decimal positions), but not successful so far.
I'd welcome every help with solving this case.
Thank you guys.

A: If $x_1, x_2,\dots, x_n$ are positive real numbers, then it seems to me like the "proportion" you are looking for, $p_i$, can be calculated as
$$p_i = \frac{x_i}{\sum_{j=1}^n x_j}$$


text:
Q: Using multiple WHERE clauses with this query not returning correct result set I have the following table, it contains information about clients and the products they have. I am looking to write a query that will return clients with specific products that I am looking for.
Create Table
CREATE TABLE [dbo].[MainTable](
    [Client_Name] [nChar](10) NULL,
    [Client_ID] [int] NULL,
    [Product_Name] [nChar](10) NULL,
    [Client_State] [nChar](10) NULL
) ON [PRIMARY]

Examples of Insert Statements I've used
INSERT INTO dbo.MainTable VALUES ('Client_1', 1, 'Suite 09', 'VA')
INSERT INTO dbo.MainTable VALUES ('Client_2', 2, 'Suite 07', 'VA')

Table
Client_Name    Client_ID    Prod_Name    Client_State
------------------------------------------------------
Client_1       1            Suite 09      VA
Client_2       2            Suite 07      VA
Client_2       2            Suite 08      VA
Client_3       3            Suite 10      VA
Client_4       4            Suite 10      VA
Client_4       4            Suite 11      VA
Client_5       5            Suite 11      VA

So let's say I want all clients with the products, 'Suite 10' AND 'Suite 11'. Client_4 matches this criteria.
The query I tried returns an empty result set:
SELECT [CLIENT_NAME]
FROM [PRODUCTDB].[dbo].[MainTable]
WHERE Product_Name = 'Suite 09' AND Product_Name = 'Suite 10'

If I try an OR clause, I get results which I do not want. For example, substituting an OR for the AND clause in the above query gives me:
Client_1 * This client does not have Suite 10, only Suite 09
Client_3 * This client does not have Suite 09, only Suite 10
Client_4 * This client is correct, it has both Suite 09 and Suite 10.

What it seems like I'll need to do is write a query for one product, and then write another query for the other product using the results of the first query. Hopefully there's a more elegant solution!

A: Use OR instead of AND like:
WHERE Prod_Name = 'Suite09' OR Prod_Name = 'Suite08'
                            ^^

Which means either the Prod_name is Suite09 or its Suite08
In your case with AND, you meant to say Prod_Name should be both at the same time which is not possible.


text:
Q: WCF Rest upload file size issue Initially, my upload was limited to 64KB.
I have gone through multiple suggestions on web and on this site, and made following changes
 <bindings>
  <webHttpBinding>
    <binding name="StreamedRequestWebBinding"
             maxReceivedMessageSize="10485760"
maxBufferPoolSize="10485760" maxBufferSize="10485760" closeTimeout="00:03:00"
openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:03:00">
      <readerQuotas maxDepth="32" maxStringContentLength="10485760"
maxArrayLength="10485760" maxBytesPerRead="10485760" />
      <security mode="None" />
    </binding>
  </webHttpBinding>
</bindings>

<endpoint address="" bindingConfiguration="StreamedRequestWebBinding" behaviorConfiguration="web" binding="webHttpBinding"
      contract="DatingService.IRegisterService1" />

 <system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime executionTimeout="240" maxRequestLength="10240" />
<pages validateRequest="false" />

  </system.web>

After making above changes, I am able to upload max of 4MB, though I have given max allowed size to 10MB. We havent ported application to IIS yet, and testing from visual studio only. Where did I go wrong? Pl suggest

A: 4mb is a default max post size for the application server. You can change this
http://msdn.microsoft.com/en-us/library/e1f13641(v=vs.71).aspx


text:
Q: How to read, write and list folders and files in google bucket? I would like to read/write files in Google Cloud Storage bucket with Python.
Suppose I have a folder in gs://my_project/data.

*

*How to list the folders and files in the above folder?

*How to read and write files?

A: There are several ways to perform these operations. The most common one is to use the native Google Cloud Storage API for Python.
In particular, step 0 to use this API is to set up authentication to GCP, which consists in setting up a service account, downloading its json credentials and set an environment variable pointing to it:
export GOOGLE_APPLICATION_CREDENTIALS="[PATH-TO-JSON-CREDS]"

1. Listing files and folders
In GCS, there is no notion of a "directory"/"folder". There are only buckets and blobs/objects. Nevertheless, the / in blob names are usable to emulate a folder-like hierarchy.
To list blobs from gs://my_project/data:
from google.cloud import storage

client = storage.Client()
bucket = client.bucket('my_project')

blobs = list(bucket.list_blobs(prefix='data/'))

2. Reading and writing files
To read from the first blob listed in gs://my_project/data.
target_blob = blobs[0]

# read as string
read_output = target_blob.download_as_string()

To write to new blob, I have found no other way than to write to a local file and upload from file.
target_blob = bucket.blob('new_blob.txt')

local_tmp_path = 'tmp.txt'

# write string
with open(local_tmp_path, 'w') as f:
   f.write('Hello World')

with open(local_tmp_path, 'r') as f:
   target_blob.upload_from_file(f)

A: In order to list/read files, the code that @syltruong suggested didn't work for me for some permission error. I had to change the code to
storage_client = storage.Client.from_service_account_json('./path_to_json')
bucket = storage_client.bucket(bucketname)
blobs = list(bucket.list_blobs(prefix='data/'))

which worked fine.


text:
Q: Is it possible to create constants in Progress-4GL? Good afternoon,
Is it possible to create constants in Progress-4GL?
The same question has been asked here, but there the question is based on object oriented programming (which I'm not doing).

A: There is no constant keyword in ABL.
The simplest way to create constant values is using static properties. These are available in any code, even procedural.
class ConstantValues:
  define static public PI as decimal initial 3.14159 get.
end class.

You could add a private setter and do the assignment in the static constructor, instead of the initial value.
If you can't or don't want to use this approach, you can use preprocessors. If you need these values shared then define the preprocessors in includes and use those in your programs (even classes).
But that's - to me - more work than it needs to be if you're creating new constant values.

A: Even if not a constant and also possibly quite old school you can define precompiler statements that can work as a constant.
There's a possibility for global (&GLOBAL-DEFINE) and not global (&SCOPED-DEFINE)
Its also possible to undefine, check defined and other basic things.
These are define on compilation time so they cannot be changed dynamically when the program is running.
&SCOPED-DEFINE const1 1
&GLOBAL-DEFINE const2 hello

DISPLAY {&const1} "{&const2}".


text:
Q: How to download the final url from the campaign level in Google Ads API using GAQL query I am trying to get data for the conversion and the assigned final url using Google Ads API & GAQL. From what I saw, it is possible to click such a report using graphical tools, but in the API I do not see any way of combining this type of data into one report.
From the campaign level, it is not possible to simply add the final url field.
https://developers.google.com/google-ads/api/fields/v7/campaign_query_builder
So my question is: \how can I get conversion data + final url from Google Ads using GAQL or AdsApp?
My current code, or rather query, looks like this:
...
var report_conversion = AdsApp.report(
  "SELECT campaign.name, " +
  "segments.conversion_action_name, " +
  "metrics.conversions, metrics.conversions_value" +
  "FROM campaign WHERE segments.date > '2021-01-01' AND segments.date < '2021-01-31'"
);

report_conversion.exportToSheet(sheet)

A: Yes, the final URL is not a campaign attribute/resource. It's an attribute of an ad.
https://developers.google.com/google-ads/api/reference/rpc/v8/Ad
report_request = f'''SELECT ad.final_urls[]
                            FROM Ad'''

Think of what you're doing as querying the campaigns table, when you really want to query the Ad table. Be aware that not all metrics are available at this level.


text:
Q: vuejs v2 pass data to component and update parent when changed What I want to build is a Form which can detect errors from its Inputs. The inputs are rendered (in my current setup) in a  section in the form. But after hours of work, it doesn't work.
What is the best approach to make the concept will work? Should I used slots for this or is there a other way?
This is my code:

//Form.vue
<template>
<form method="POST" action="/projects">

<slot></slot>

    <button class="button is-primary">Create</button>

</template>

//Input.vue
<template>

    {{label}}

    <input type="text" id="name" name="name" class="input">

</template>

Implementation in the browser:
<vue-form :fields="{'name': 'piet', 'description': 'arie'}">
    <vue-input
        label="The Name"
        name="name"
    ></vue-input>

    <vue-input
        label="The Description"
        name="description"
    ></vue-input>
</vue-form>

A: you can use custom event.
in cild component
this.$emit('EventName', someData)

and in parent you can handle it with
v-on:EventName="doSmth"

A: From the documentation:

In Vue.js, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events. Let's see how they work next.

How to pass props
Following is the code to pass props to child component: (with v-model value is passed as props, or with v-bind in myMessage parentMsg is passed as props)

  <input v-model="parentMsg">

  <child v-bind:my-message="parentMsg"></child>

How to emit event
Following is how you update parent: whenever in child you increment: you intimate parent by calling this.$emit('increment') which is handled by parent.
HTML:

{{ total }}

  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>

JS:
Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})