text:
Q: org.jboss.weld.exceptions.IllegalArgumentException: WELD-001456 : Argument resolvedBean must not be null This question is purely based on this question.

I have created a sendbox Java EE application in WildFly 10.0.0 final using Hibernate 5.1.0 final / Weld 2.3.2 final. The project contains nothing other than a single entity class, an entity listener and one plain blank local stateless session bean - no complexity, no extra dependency at all.
It is a standard NetBeans project built and deployed by Apache Ant. Thus, it does not use Apache Maven.
The entity listener is registered in /META-INF/orm.xml.
<entity-mappings version="2.1"
                 xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd">

    <entity class="entity.Discount">
        <entity-listeners>
            <entity-listener class="entity.listener.DiscountListener"/>
        </entity-listeners>
    </entity>
</entity-mappings>

The persistence.xml file.
<persistence version="2.1"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="Test-ejbPU" transaction-type="JTA">
        <jta-data-source>java:jboss/datasources/datasource</jta-data-source>
        <mapping-file>META-INF/orm.xml</mapping-file>

        <class>entity.Discount</class>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
    </persistence-unit>
</persistence>

The local stateless session bean is left completely blank (contains nothing, not even a single line).
@Stateless
public class TestBean implements TestService {

}

The entity listener contains an injection point of the above stateless session bean (this is also not coded).
public class DiscountListener {

    @Inject
    private TestService service;

    @PostPersist
    public void postPersist() {

    }
}

The deployment process terminates abruptly with the following exception.
20:17:54,656 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 116) MSC000001: Failed to start service jboss.persistenceunit."Test.ear/Test-ejb.jar#Test-ejbPU": org.jboss.msc.service.StartException in service jboss.persistenceunit."Test.ear/Test-ejb.jar#Test-ejbPU": javax.persistence.PersistenceException: [PersistenceUnit: Test-ejbPU] Unable to build Hibernate SessionFactory
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:172)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:117)
    at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:182)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: Test-ejbPU] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:884)
    at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:154)
    ... 7 more
Caused by: org.jboss.weld.exceptions.IllegalArgumentException: WELD-001456: Argument resolvedBean must not be null
    at org.jboss.weld.util.Preconditions.checkArgumentNotNull(Preconditions.java:40)
    at org.jboss.weld.manager.BeanManagerImpl.getInjectableReference(BeanManagerImpl.java:794)
    at org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:92)
    at org.jboss.weld.util.Beans.injectBoundFields(Beans.java:378)
    at org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:389)
    at org.jboss.weld.injection.producer.ResourceInjector$1.proceed(ResourceInjector.java:70)
    at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:48)
    at org.jboss.weld.injection.producer.ResourceInjector.inject(ResourceInjector.java:72)
    at org.jboss.weld.injection.producer.BasicInjectionTarget.inject(BasicInjectionTarget.java:121)
    at org.hibernate.jpa.event.internal.jpa.ListenerFactoryBeanManagerStandardImpl$ListenerImpl.<init>(ListenerFactoryBeanManagerStandardImpl.java:93)
    at org.hibernate.jpa.event.internal.jpa.ListenerFactoryBeanManagerStandardImpl$ListenerImpl.<init>(ListenerFactoryBeanManagerStandardImpl.java:82)
    at org.hibernate.jpa.event.internal.jpa.ListenerFactoryBeanManagerStandardImpl.buildListener(ListenerFactoryBeanManagerStandardImpl.java:68)
    at org.hibernate.jpa.event.internal.jpa.CallbackBuilderLegacyImpl.resolveCallbacks(CallbackBuilderLegacyImpl.java:170)
    at org.hibernate.jpa.event.internal.jpa.CallbackBuilderLegacyImpl.buildCallbacksForEntity(CallbackBuilderLegacyImpl.java:69)
    at org.hibernate.jpa.event.spi.JpaIntegrator.integrate(JpaIntegrator.java:134)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:276)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:881)
    ... 9 more

20:17:54,671 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 2) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"Test.ear/Test-ejb.jar#Test-ejbPU\"" => "org.jboss.msc.service.StartException in service jboss.persistenceunit.\"Test.ear/Test-ejb.jar#Test-ejbPU\": javax.persistence.PersistenceException: [PersistenceUnit: Test-ejbPU] Unable to build Hibernate SessionFactory
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: Test-ejbPU] Unable to build Hibernate SessionFactory
    Caused by: org.jboss.weld.exceptions.IllegalArgumentException: WELD-001456: Argument resolvedBean must not be null"}}

According to this issue status, this issue has however been fixed in Hibernate 5.1.0 final.

Additional :
The application succeeds, when a true value is given in,
<exclude-unlisted-classes>true</exclude-unlisted-classes>

and the annotation approach is used to mark the entity listener avoiding the XML mapping in orm.xml i.e. when the Discount entity is decorated with @EntityListeners(DiscountListener.class).
Doing so is however disallowed in my environment, since I use a class library to bridge common functionalities across two modules namely the EJB module and the WAR module in which I have placed entity classes in the class library (as far as I am concerned, injection points in a class library do not work as it does not have a Java EE environment - it is not qualified and consequently, entity listeners along with @EntityListeners(ListenerClass.class) cannot be used therein).
Obviously, entity classes would need to be added to both the places namely the EJB module and the class library, if that approach were to be adopted because the class library would also need entity classes to be present on its compile-time class-path. This will in turn result in java.lang.ClassCastException: com.example.Entity cannot be cast to com.example.Entity, since there are duplicate entity classes on the run-time class-path.
► This nevertheless succeeds on GlassFish Server which does not complain about the duplication.
Entity classes along with the JPA static metamodel have been placed in a class library and entity listener classes have been placed in the associated EJB module and registered in /META-INF/orm.xml (EJB module).

The approach mentioned throughout the question succeeds on GlassFish Server / EclipseLink. Therefore, I expect it to work on WildFly / Hibernate.
What may be the possible way to go about? It should function in anyway without breaking the Java EE contract - not necessarily the only way I have mentioned but keeping the class library intact is essential.
P.S. The project does not use Apache Maven which does not support a class library as far as I know.


text:
Q: Trouble designing and understanding lowpass filter in analog (mixer) phase-locked loop (PLL) I'm trying to design a software-based PLL that mimics the behavior of an analog PLL based on a 4-quadrant mixer as the phase detector (PD). The input signal is a sinusoid of unknown frequency between \$1\,\text{kHz}\$ and \$100\,\text{kHz}\$. The voltage-controlled oscillator (VCO) should generate a sinusoid with the same frequency and amplitude but with a phase-lag of \$90^{\circ}\$. I've been having considerable trouble getting this to work. I think my primary issue is in understanding how the phase error signal (integrated/low-passed mixer output) works. So, I decided to try to develop an intuition for the math. Unfortunately, this isn't helping. I've described my process below.
I've restricted myself to a simplified example in which my input signal and VCO-generated reference are unchanging and the reference can have a different frequency and phase shift from the input. Of course this is unrealistic in the sense that PLL's rely on feedback, but I'm trying to develop an intuition for the PD output for different reference signal phase shifts and frequencies. What I've done is compute
\$
\begin{equation}
\frac{1}{t_2-t_1}\int_{t_1}^{t_2} s(t)r(t)dt
\end{equation}
\$
where \$s(t)=\sin t\$ is the input signal and \$r(t)=\sin(ft+\phi)\$ is the reference signal. Then for each of several values of \$f\$, I've plotted this integral for \$\phi\in[0,2\pi]\$.
I started out with the signal and reference at the same frequency (i.e., \$f=1\$). I generated the plot in sagemath with the following command:
plot(integrate(sin(t)*sin(1*t+var('x')), (t, 0, 10))/10, x, 0, 2*pi)

The result is

So far so good. This tells me that the error signal is 0 when \$\phi=-\pi/2\$. Additionally, if the phase wanders slightly lower than \$-\pi/2\$ the error signal goes negative, decreasing the VCO frequency and thus pushing to next zero-crossing a little later, thus bring the phase-shift back to equilibrium. Same for wandering above the equilibrium point. I think this is all fine so far.
The problem arises when I increase the frequency of the reference. For example, let's take a bit of an extreme case, \$f=10\$. Even though this might seem a bit extreme, given the bandwidth mentioned earlier this is possible. Here's the same plot for that:
plot(integrate(sin(t)*sin(10*t+var('x')), (t, 0, 10))/10, x, 0, 2*pi)

I'm not so worried about the angle where this phase locks (feedback will mean this isn't a stable frequency, so I'm pretty sure the locations of the zero-crossings in this plot is essentially irrelevant). What worries me more is the magnitude of the error signal: it's 100x lower than in the same frequency case. How can the frequencies converge and then phase lock with such a small error? This result makes sense to me mathematically since we're essentially integrating over a difference frequency, so when the frequencies are the same we get a constant that doesn't zero out. When the frequencies aren't the same we're integrating over a much lower frequency sinusoid. Nevertheless, I'm not making the connection between this fact and how to fix it. I can change the integration period, but I don't see how I can do that to accommodate the full input frequency range.
Is the loop filter more complicated than a simple integrator? Should I be implementing it another way? I can add a proportional term, but then the error signal will oscillate a lot. Is it simply a balancing act between the proportional and integral terms? How can I determine these? I've fiddled around with quite a few combinations and all I've managed is to get it to kind of work at one frequency and fail at others. Are there any algorithms for how to accomplish this, or other resources/textbooks/articles I could use for this? Have I misunderstood the capabilities of PLLs? Are they not able to lock to an unknown frequency in a wide range?
It's probably worth mentioning that I think this problem would be much easier in an unrealistic ideal case where I had the absolute phase difference between the signals. Then my error signal would always increase in one direction and decrease in the other rather than oscillate as it does here, which I think is what makes this case challenging.

A: Without a true phase-frequency-detector, you will be plagued with FALSE LOCKS.
Consider using a 2-flipflop-one-NAND_reset PFD.
You need to make the "analog" signals --- Freference and Fvariable --- be logic level signals. If your FFs are CML current mode logic, as little as 0.2 volts will suffice, but need to be "squared up" thru a limiter.
===================================
if you are counting "zero crossings" to allow presetting the F_reference to the approximately correct frequency, then you certainly have already converted the (noisy?) analog signal to rail_rail (or at least logic_0 to logic_1) levels.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Console logs of Cordova app not appearing in logcat once it is signed While developing I am able to remotely debug an APK generated by Apache Cordova using console.log's and watching their output in chrome://inspect/#devices.
Once signed however, I seem to be unable to see any of those console.log's in the logcat file.
What am I doing wrong?

A: Looks like that feature was removed on cordova-android 9
https://github.com/apache/cordova-android/pull/950


text:
Q: Using QChart in visual studio I am trying to use the Qt QChart to plot a line graph. I am using visual Studio 2013 with Qt 5.8. I created a simple QApplication. When I paste  QLineSeries *series it says QLineSeries is undefined. How can I fix this?
#include "QtGuiApplication2.h"
#include <QtWidgets/QApplication>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QtGuiApplication2 w;

    QLineSeries *series = new QLineSeries();

    w.show();
    return a.exec();
}

A: you need to link against QT5Charts under:
general properties
- Linker
  - Input
   - add the path: e.g. C:\Libraries\Qt\Qt5.7.0\msvc\lib\Qt5Chartsd.lib

I suppose, you don't forget to add the namespace?
using namespace QtCharts;

if you work with cmake, just add this to your cmake file:
find_package(Qt5Charts)
target_link_libraries(${targetName} Qt5::Charts)


text:
Q: Do both lines return a string? I am currently following through the beginner Codebat track.  Both pieces of code work however is there anything fundamentally wrong/different between the two ways of writing the below code?
thanks,
def mine(myStr, x):
    myResult = myStr * x
    return myResult

def codebat(thierStr, i):
    codeResult = ''
    for i in range(i):
        codeResult += thierStr
    return codeResult

A: import string  # string.ascii_letters = 'abcde...ABCDE...'

def mine(s, x):
    return s * x  # fixed your code so it multiplies by x, not 4

def theirs(s, x):  # renamed but the same as codebat
    res = ''
    for _ in range(x):
        res += s
    return res

We can see they give the same results
mine(string.ascii_letters, 10) == theirs(string.ascii_letters, 10) # --> True

We can test the time efficiency of these functions however
%timeit mine(string.ascii_letters, 1000)
2.27 µs ± 9.69 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit theirs(string.ascii_letters, 1000)
202 µs ± 4.24 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

As you can see mine is almost 100 times more efficient because under the hood python pre-allocates the memory needed for the new string. In theirs it has to keep reallocating memory each time the string length is increased.


text:
Q: File.AppendAllText throws FileNotFoundException I am working on Internet explorer add-on, I wrote a dll that attached to the browaswer, Ihave some event, inside of ot I am writing to some text file with File.AppendAllText, this throws FileNotFoundException, I am using AppendAllText in other places in my code, and there if the file is not exist it creates a new file, my question is why this exception throwen and how can I avoid that.
I have found this answer, but it doesnt say how to avoid the error (i.e to write the file without getting this exception), also didn't understad that this is a "documentation error"
Here file fath:
static string assem = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
static string logPath = Path.Combine(assem, "Log.log");

Here the line that thows the error:
File.AppendAllText(logPath, "some text" + Environment.NewLine);

Here the exception:

A: Probably IE blocks the extension to write to a local file, try to uncheck the "Protected mode" int the browser
Tools --> Internet Options --> Security --> unckeck "Enable Protected Mode"

A: The exception type is a bit misleading; in some ways it'd be better to throw a ArgumentException perhaps.  The reason you're seeing this exception is the path you're supplying is not a valid file path (either it contains an invalid character or it's >255 characters).
Inspect the value of the path at this point in the code in a debugger, open up a command prompt and issue the following command to see if you can write to that path:
echo "Testing creating a file at this path" > "C:\Path\To\Your\File.txt"

I'll hasten a guess that the path contains a directory which does not exist (e.g. your path is C:\Path\To\Your\File.txt but the Path directory does not contain a To subdirectory).


text:
Q: Ionic Android Release build kills HTTPS request The problem with building my app is that when I build it with
cordova clean android
cordova build --release android

+ sign + zipalign

the app fails to process any http / https request.
When I build with
cordova build --debug android

the requests work, but I can not upload it to the app store because it's a debug build.
I would like to compare both final builds to identify the culprit. How can I compare the now binary AndroidManifest.xml files for instance? I found this post, yet I can not make any sense out of it for myself.

A: What is the error that you get on the console, when running the release apk?
Generally, instead of running
ionic cordova build android --release

you should run
ionic cordova build android --release --prod

You can also open the platforms/android directory with Android Studio and run it from there (to have a clearer Logging output)


text:
Q: Alternatives to presentational html tags I have a headline on my website and i have to break some words and place on the second row and some words are in different colour. Is there a way i could do that without using the presentational html tags like line break  and emphasis ? Im very new in html and css.

I AM A SURFER
 WHO LOVES THE BEACH,
 SUNSET AND ICE CREAM.

A: I would suggest using span that you will then display as blocks.
HTML:

hello>How are you

CSS:
p span
{
    display: block;
}

A: p {
  white-space: pre-line;
 }

HTML:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

Note: I just pressed enter key for new line.

A: Using the existing class and tag you've specified, you could roll with something like the following:
CSS:
span.header h1 {
    margin: 0px;
    padding: 0px;
}

HTML:

I AM A SURFER

WHO LOVES THE BEACH,

SUNSET AND ICE CREAM.

A: If it is (absurdly) forbidden to use em and br markup, then you can use the span element and CSS rules that correspond to the default rendering of those elements:

...

I AM A SURFER
WHO LOVES THE BEACH,  SUNSET AND ICE CREAM.


text:
Q: Result Code is always 0 as result of uninstallation Intent in android From my Application I am trying to uninstalling an application by using the code
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE);
uninstallIntent.setData(Uri.parse("package:" +packageName));
uninstallIntent.setAction(Intent.ACTION_VIEW);
startActivityForResult(uninstallIntent,UNINSTALL_APPLICATION);

as per I am starting the activity for result I want to perform different actions on the basis of user's input like if  cancelled or clicked on ok.
As I expected the result code of clicking ok will be RESULT_OK and clicking on cancel will be RESULT_CANCEL, but in actual in both cases I am getting RESULT_CANCEL.
So how can I differentiate the user's input.
Thanks!

A: Per the API, ACTION_DELETE doesn't return anything. If nothing is returned, then the result status will be RESULT_CANCEL.
Your best bet is to set up an Intent Filter/ Broadcast Receiver listening for the  ACTION_PACKAGE_FULLY_REMOVED intent. There is a question on such previously asked here.

A: After a lot of thoughts in mind finally i have got the solution tricky one.
How I Implemented at the time of calling the Uninstall Intent i have saved the package name in a preferences file by using
SharedPreferences prefs;
prefs.edit().putString(DELETE_PACKAGE_NAME, packageName).commit();

And what i have done in OnActivityresult i have just checked whether the application with saved package name still present if it is means user has clicked on Cancel else he clicked Ok.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

 if(requestCode==DELETE_APP){

    String requestedPackageName=prefs.getString(DELETE_PACKAGE_NAME, "");

    boolean isPresent=GCMIntentService.isAppPresent(requestedPackageName, this);

    if(isPresent){

      //user Clicked on Cancel
    }else{

      //user Clicked on Ok
    }

 }

}

Code for Checking the application presence
public static boolean  isAppPresent(String packageName,Context context) {

  try{
    ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, 0 );
    return true;

} catch( PackageManager.NameNotFoundException e ){

   return false;
}

 }

Thanks.
UPDATED:
As platform changed a lot since I answered this here is the update
Now you can use an intent where you can explicitly define whether it should return a result or not
val intent = Intent(Intent.ACTION_UNINSTALL_PACKAGE).apply {
            data = Uri.parse("package:$packageName")
            putExtra(Intent.EXTRA_RETURN_RESULT, true)
        }
        startActivityForResult(intent, YOUR_REQUEST_CODE_HERE)

Documentation : https://developer.android.com/reference/android/content/Intent.html#ACTION_UNINSTALL_PACKAGE
This will return a result a
From the documentation :

The returned result code will be Activity.RESULT_OK on success or
  Activity.RESULT_FIRST_USER on failure.

Starting API 21 Android added a helper method
PackageInstaller.uninstall (String packageName,
                IntentSender statusReceiver)

Read more about the changes in the link below, stating from Android Q the above updated approach is also deprecated.
https://developer.android.com/reference/android/content/pm/PackageInstaller.html#uninstall(java.lang.String,%20android.content.IntentSender)

A: Try this
Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
intent.setData(Uri.parse("package:" + packageName));
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, Constants.FROM_UNINSTALL);


text:
Q: StringBuilder implements Comparable but does not override equals I don't understand this line from javadoc (under the subheading "API note"):

StringBuilder implements Comparable but does not override equals. Thus, the natural ordering of StringBuilder is inconsistent with equals.

I am a beginner in Java so could you explain this in a simple way?

A: That means StringBuilder.compareTo() and StringBuilder.equals() don't always agree.
var sb1 = new StringBuilder("foo");
var sb2 = new StringBuilder("foo");
assert sb1.compareTo(sb2) == 0;      // as you would expect.
assert sb1.equals(sb2) == true;      // surprise - it fails

Now it gets a bit more confusing:
var map = new HashMap<StringBuilder, String>();
map.put(sb1, "lorem ipsum");
assert map.size() == 1;
map.put(sb2, "dolor sit amet");
assert map.size() == 1;            // fails - it's 2

var set = new TreeSet<StringBuilder>();
set.add(sb1);
assert set.size() == 1;
set.add(sb2);
assert set.size() == 2;           // you'd think this should be 2 but it fails!

That's because HashMap works with equals() whereas SortedSet with compareTo().

NOTE 1: on equals()
StringBuilder extends Object, which means it inherits Object.equals(); but it does not override equals(), which means StringBuilder.equals() is actually Object.equals().
Object.equals() in turn is basically ==, ie it returns true if and only if the two objects are the same memory address.
Object.equals() java doc

NOTE 2: why?
Only starting from JDK11, StringBuilder implements Comparable. Any accompanying change in equals() could have caused some older client code to break; so, I'd think, following the Java tradition of keeping things backward compatible they dropped the idea.


text:
Q: Laravel использование this->field в relationship У меня есть таблица havings, rigs и parts.
В таблице havings есть поле part_id, по которому можно получить доступ к part, которая привязана к havings.
В таблице rigs всё немного сложнее - несколько полей: GPU_id, RAM_id ...
Итак, в модели Having определено отношение hasOne для модели Part. Как определить отношение в модели Having для модели Rig?

 public function rig() {
    return $this->hasOne(Rig::class, $this->part->type . '_id', 'id');
}

Я пробовал так, но это работает почему-то только для GPU_id, если type = RAM, то rig = null.
А если вывести dump($this->part->type), то выводится 1 строка - GPU
Вот мои таблицы (между having и part есть таблица part_shop, но это роли не играет в этом вопросе)


text:
Q: Naming tables using middle dot in MYSQL? Could it cause problems to name a table using middle dots, like this:
tbl_prod·prov;

A: The rules are explained at Schema Object Names:

Identifiers are converted to Unicode internally. They may contain these characters:

*

*Permitted characters in unquoted identifiers:

*

*ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)

*Extended: U+0080 .. U+FFFF

*Permitted characters in quoted identifiers include the full Unicode Basic Multilingual Plane (BMP), except U+0000:

*

*ASCII: U+0001 .. U+007F

*Extended: U+0080 .. U+FFFF

*ASCII NUL (U+0000) and supplementary characters (U+10000 and higher) are not permitted in quoted or unquoted identifiers.

*Identifiers may begin with a digit but unless quoted may not consist solely of digits.

*Database, table, and column names cannot end with space characters.

The · character is U+00B7 MIDDLE DOT so it fits the definition for Extended in quoted identifiers.
Said that, I can think of two potential problems:

*

*Object names sometimes needs to be mapped to filesystem objects. We can speculate that MySQL has done things right in all supported platforms but it makes me feel uneasy.

*If you happen to run a SQL query in a client/connection that's not correctly configured, or you paste the query from the clipboard, you risk using the wrong character.


text:
Q: Xcode: Detecting when a navigation controller implemented "back button" is pressed Scenario
I have an app with a navigation controller. When the navigation controller pushes another controller onto the stack, in the upper left corner of the screen it shows the back button "<(title of the last view controller)".
What I need
I need something like (pseudo code)...
-(void)detectedBackButtonWasPushed {

    NSLog(@"Back Button Pressed");

    //Do what I need done

}

Question
Because this button is created by the navigation controller and I did not create this button in storyboards, how do I get the back button 'hooked up' to a method like this?
examples of what Ive tried for Oleg
-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

    UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"notification"];

    if (viewController == vc) {

        NSLog(@"BACK BUTTON PRESSED");
    }
}

Is this how I'm supposed to do it? Cause this doesn't work.

A: Use  viewWillDisappear to detect this.
-(void) viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound)
    {
        [self backButtonPressed];
        [self.navigationController popViewControllerAnimated:NO];
    }

    [super viewWillDisappear:animated];
}

-(void)backButtonPressed
{
   NSLog(@"YEA");
}

A: Previously, I have solved this by setting the navigationBar leftItem to be a back button with a custom selector that dismisses the view along with whatever else it needed to do.
I might also suggest looking at the back button item and adding a target:self that is called on touch.


text:
Q: How faster is an 'if' construct compared to an immediate 'if' statement (IIF) and when should I use it? How does the traditional if statement compare with that of the immediate if statement (IIF, the one usually written as condition ? value_if_true : value_if_false) in terms of speed of execution?
Also, in what scenarios should we be ideally using the IIF?

A: EDIT: WRONG: Most likely, there is no measurable difference in terms of speed.
CORRECT: Since IIf is a library function in VB, both truepart and falsepart are evaluated, so if one of those is expensive to evaluate but eventually not choosen, it might be much slower than a conventional If.
Therefore, you should be using it when it makes your code more compact and readable.
In many cases, using iif (or the ternary ?: operator in C-like languages) makes it possible to avoid introducing an intermediate variable (or code replication)
Consider:
A = B + C + IIf(D<=3, D, 3)

vs.
If D<=3 Then
  E = D
Else
  E = 3
End If

A = B + C + E

or
If D<=3 Then
  A = B + C + D
Else
  A = B + C + 3
End If

A: As far as performance goes: In a fully-compiled language like C or C++, with optimizations on, the difference is probably zero. In other languages (interpreted, byte-code-compiled, or jit-compiled) there may be a difference, but 1. it's not going to be much and 2. it's not going to be your bottleneck. There are exceptions, but those are rare, and if you encounter one of them, you're probably fiddling with fine-grained profiling and instruction-level optimizations; in all the other cases, either is going to be fast enough.
So, as always, your first choice should be to optimize for readability, not for runtime performance. Which brings us to the question when you should use one or the other; well, opinions differ. One camp says the ternary operator simply shouldn't be used at all, for clarity's sake; and they certainly have a point, because it has the tendency to make for really complicated one-liners, especially if you nest it, but also because its precedence can lead to undesirable results. However, I think there are situations where a ternary operator makes the code more readable, and I don't see anything wrong with using it in such a situation; a textbook example is simple text pluralizing:
printf("%i %s deleted.", num_files, (num_files > 1) ? "files" : "file");

The same code written with an explicit if statement would have taken 5 additional lines without substantially contributing to readability.
That said, IIf in VB has a nasty caveat: unlike If, which is a proper language statement and evaluates only one branch, IIf is a built-in function, so both branches get evaluated, no matter what the condition says. As long as the branches don't have side effects, you won't notice, but when they do, you're in for some serious face-palming.

A: @ammoQ's answer needs something clarified, he means that the programmer doesn't have to intoduce a temporary variable, not the compiler. In all cases there'll be a temporary variable to hold the result of the conditional operator.
The real difference I know about (at least in C, C++ and Java) is that it's an expression, as opposed to a statement. In other words, it can act as an RValue (I mean a value that can be assigned to a variable). A statement doen't evaluate to a value. This makes their usage more convenient, such as:
int x = (y > 0 ? 1 : 2);

which can't be written as
int x = if (y > 0) 1; else 2;

But rather split into more than one line. This will be noticeable as the logic inside the if/else grows.

A: Micro-optimisation is rarely worth worrying about, and whether the ternary operator is executed faster than a full conditional definitely falls under the category of micro-optimisation.
Really, the ternary operator should be used when it makes the code clearer to read and thus easier to maintain and should be avoided where it makes the intent of the code more obscure and thus more difficult to maintain.
If you get to the stage where your application is not performing as well as you need it to perform, then you need to profile your application, benchmarking it with typical and worst case application loads. Only then can you see where you application is running too slowly and thus where to spend your time in optimising.
As it is, you are very unlikely to see any difference between code with uses IIf and code which doesn't, but to be sure you need to benchmark.
Finally, you have to be very careful about using the VB IIf() construct due to issues with side effects. The fact that value_if_true and value_if_false are always evaluated, irrespective of the value of the condition means that the IIf() version could behave very differently to the normal If construct it might be intended to replace.


text:
Q: How to stream video from URL with Javascript When I try to stream a video from a url, I get the following error:
Uncaught (in promise) DOMException: Failed to load because no supported source was found.

Obviously, I've tested and my source works great. Here's a simplified JS fiddle, and here's a copy of the code in that fiddle:
// Create HTML Video Element to play the video
var video = document.createElement('video');
video.addEventListener('loadeddata', function (e) {
    document.body.appendChild( video );
});

video.src = 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4';
video.crossOrigin = 'anonymous';
video.loop = true;
video.play();

What do I need to change in order to get it working?


text:
Q: How to calculate confidence bands for models with 2 or more independent variables with kapteyn.kmpfit I try to compute confidence bands for a model with two independent variables.
I use kmpfit from kapteyn package to optimize parameters and compute confidence bands. The confidence_band function does not seem to work for models with more than one independent parameters. Does anyone have an idea how to solve this problem?
For models with one indpendent parameter, everything works as expected, without any problems:
from kapteyn import kmpfit
import numpy as np
import matplotlib.pyplot as plt

#linear 1d model
def model_1d(p, x):
    a = p[0]
    b = p[1]
    return a*x + b

#data
x = np.array([0, 10, 20, 30])
y  = np.array([1.1, 1.8, 3.2, 3.0])

#optimizing parameters a and b with kmpfit
p0 = [0, 0] #start values for parameters a and b
f = kmpfit.simplefit(model_1d, p0, x, y)

#calculation of confidence band

derivatives_a = x #1st derivative of a is x
derivatives_b = np.array([1, 1, 1, 1]) #1st derivative of b is always 1
dfdp = [derivatives_a, derivatives_b]

yhat, upper, lower = f.confidence_band(x, dfdp, 0.95, model_1d)

#plots
plt.plot(x,yhat) #plot fitted model
plt.plot(x,upper,'--') #plot upper confidence band
plt.plot(x,lower,'--') #plot lower confidence band
plt.plot(x,y,'.r') #plot data points

The script works nicely. As a result, you see the fitted model with upper and lower confidence bands:
plot with upper and lower confidence bands
Below, the code is slightly changed to a 2D model, i.e. with two independent variables. This code does not work any more:
from kapteyn import kmpfit
import numpy as np

#linear with two independent variables x[0] amd x[1]
def model_2d(p, x):
    a = p[0]
    b = p[1]
    return a*x[0] + b*x[1]

#data
x = np.array([[0, 10, 20, 30], [0, 10, 20, 30]])
y  = [1.1, 1.8, 3.2, 3.0]

#optimizing parameters a and b with kmpfit
p0 = [0, 0] #start values for parameters a and b
f = kmpfit.simplefit(model_2d, p0, x, y)

#calculation of confidence band

derivatives_a = x[0,:] #1st derivative of a is x[0]
derivatives_b = x[1,:] #1st derivative of b is x[1]
dfdp = [derivatives_a, derivatives_b]

yhat, upper, lower = f.confidence_band(x, dfdp, 0.95, model_2d)

For the 2D model, parameter optimization with simplefit still works.
However calculation of confidence bands with confidence_band does not work any more.
I get following error message, indicating that the shape of the numpy array x makes problems (however, the same x works for simplefit):
File "tmp.py", line 25, in <module>
    yhat, upper, lower = f.confidence_band(x, dfdp, 0.95, model_2d)
  File "src/kmpfit.pyx", line 845, in kmpfit.Fitter.confidence_band
(src/kmpfit.c:8343)

If you have any idea how to solve this or if there are alternative python packages available, I would highly appreciate this.
Thank you!

A: You might find lmfit (http://lmfit.github.io/lmfit-py/) useful for this.  It has a robust but easy to use curve-fitting methods with its Model class, and also supports placing bounds and constraints on every Parameter.
In general, uncertainties for all variables and correlations between pairs of variables are calculated using the fast and generally reliable method of inverting the curvature matrix.  For more detailed uncertainties (and including confidence of any specified 'sigma' level), it also allows for direct (if slightly slower) exploration of the confidence levels for any variable, and can help you make 2-d maps of chi-square for a pair of
variables.
More specifically, I think what you are asking for is to generate the uncertainties in the model y from the uncertainties in the variables.  Lmfit's Model class has an eval_uncertainty() method to do this.  See
http://lmfit.github.io/lmfit-py/model.html#calculating-uncertainties-in-the-model-function  for an example.


text:
Q: How to add a business logic layer to the program? I created a program that generates numbers more and less than the number that we enter in the text line. Tell me how you can add a business logic layer to this program.
main.java
public class Main {
public static void main (String[]argc){
    GraphicalUserInterface gui = new GraphicalUserInterface();
    gui.setVisible(true);
    gui.setResizable(false);
 }
}

GraphicalUserInterface.java
import java.awt.*;
import javax.swing.*;
import java.util.concurrent.ThreadLocalRandom;
public class GraphicalUserInterface extends JFrame {

int anInt;
private JButton buttonMore = new JButton("Генерировать больше");
private JButton buttonLess = new JButton("Генерировать меньше");

private JTextField textField = new JTextField("", 5);
private JLabel labelOne = new JLabel("254");
private JLabel labelTwo = new JLabel("125");
private JLabel labelZero = new JLabel("");

public GraphicalUserInterface() {

    super("Lab1_GUI");
    this.setBounds(100, 100, 400, 150);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container container = this.getContentPane();
    container.setLayout(new GridLayout(3, 10, 10, 10));

    container.add(textField);
    container.add(labelZero);

    buttonMore.addActionListener(event -> {
        anInt = Integer.parseInt(textField.getText());

labelOne.setText(String.valueOf
 (ThreadLocalRandom.current().nextInt(anInt, 1000)));
    });

    container.add(buttonMore);
    container.add(labelOne);

    buttonLess.addActionListener(event -> {
        anInt = Integer.parseInt(textField.getText());
        labelTwo.setText(String.valueOf
          (ThreadLocalRandom.current().nextInt(anInt)));
    });
    container.add(buttonLess);
    container.add(labelTwo);
}
}

it is not clear how to add business logic to it


text:
Q: How Azure load balances scaled out App Service plan? I have one Azure App Service in which I have created 5 instances using App Service Plan
Scale Out option. Now I am not sure how does Azure load balances requests between this instances? I am not seeing any load balancer for it.
Also how can I know that which request is being served by which instance?

A: The load balancer is created automatically and you can't see it.
Basically it sends the requests to instances at random, though it can be made "sticky" with ARR Affinity.
You can find the setting in the App Service's Application Settings:

If it is on, the load balancer will attach a cookie to responses if they don't already have it.
It makes it so that future requests hit the same instance.
Though of course if the instance is no longer there (because of auto-scale for example), then it will again go to a random instance.
The WEBSITE_INSTANCE_ID environment variable can tell you in the back-end which instance is handling the request.
You can find a list of available variables here: https://github.com/projectkudu/kudu/wiki/Azure-runtime-environment


text:
Q: Set up sftp to use password but ssh not to use password Is it possible to set up a user on ubuntu with openssh so that ssh does not use password authentication but sftp does?
I assume that if I change /etc/ssh/ssh_config to have PasswordAuthentication yes this makes is possible for users to use passwords to login with both ssh and sftp.
Edit: My purpose here is to let some users sftp with a password instead of a keyfile.  But I do not want ssh users to be able to login with a password, I want them to have to use a keyfile.  If it helps, I do not need the sftp users to be able to login, they only need to do sftp.

A: As I understand you have (at least for this particular problem) two distinct groups of users, one being able to login via SSH and get an interactive shell (let's call the group ssh) and one being able to login via SFTP and only get an SFTP shell (let's call the group sftp).
Now create the groups ssh and sftp on your system with groupadd, put the respective users in the groups (gpasswd -a $USERNAME $GROUPNAME) and append the following lines at the end (this is important!) of your sshd_config located at /etc/ssh/sshd_config:
Match Group sftp
  PasswordAuthentication yes
  # Further directives for users in the "sftp" group

Match Group ssh
  PasswordAuthentication no
  # Further directives for users in the "ssh" group

Read about the Match directive in sshd_config(5) and about the allowed patterns in ssh_config(5).
You'll also have to restart the ssh process for this to take effect:
sudo /etc/init.d/ssh restart

A: No, and I don't see how this would improve security, so what would be the point?
authorized_keys can allow different commands for different keys, if that's what you're after. Otherwise, you have the option of creating several accounts and using acls or sudo.

A: Taking a stab in the dark here, but you may find this thread interesting.
It is fair to jail my SFTP users to their home directory?


text:
Q: Python Regex Email Extraction - Suffix & Prefix Handling I've written the following Python code which will extract emails from a comma separated list of emails in the Email field and remove invalid emails from it:
invalid_emails = ['jane_d', 'janedoe', 'jane.doe', 'jdoe', 'j.doe', "j-d", "jdoe", "d.jane", "adacompliance", "jane.d", "d-jane", "doe", "last", "janed", "doe-jane", "beyondmenu", "doejane", "j_doe"]
    for row in data:
        emails = re.findall(r'[\w\.-]+@[\w\.-]+', row['Email'])
        emails = [email for email in emails if not any(invalid in email for invalid in invalid_emails)]
        emails = [email.lstrip("0123456789-") for email in emails if len(email) >= 5]
        print("Emails are", emails)
        for i, email in enumerate(emails):
            if i <= 5:
                field_name = f'Email_{i + 1}'
                clean_email = email.replace("mailto:", "")
                match = re.search(r'[\w\.-]+@[\w\.-]+', clean_email)
                if match:
                    cleaned_email = match.group()
                    row[field_name] = cleaned_email
                    if field_name not in new_fields:
                        new_fields.append(field_name)

The problem is this doesn't catch several kinds of invalid emails:

*

*iz@rz, Ay@_f, oTn@ퟭJ

*SUFFIX ERRORS: info@somewebsite.comopen (a valid email, should be extracted as info@somewebsite.com)

*PREFIX ERRORS Berkeley510-525-someguy@gmail.com (a valid email, should be extracted as someguy@gmail.com`)

*Instagram@somethingfCONTACT692 (this is not a valid email as it does not have a domain)

*hello@somethingrandomFriendsPhotosVideosPhotosSee (not a valid email as no domain)

*bob@somesite.com2020-01-20T22 (another valid email but followed by a date)

How can I adjust my script to account for this?


text:
Q: Ubuntu: Screen resolution doesn't fit size of monitor (Vmware) I have just installed ubunto in Vmware Player and it works great, but all of the resolutions it gives me there isn't one to fill the entire screen.
I was scouting around the net and found this,
- Open up VMWare, don't boot up Windows yet.
- Go to "View" and select "Autofit window" and "Autofit Guest".
- Close VMWare.
- Go to the terminal and do:
sudo gedit ~/vmware/preferences
- Now where it says:
pref.autoFitFullScreen = "fitHostToGuest"
change it to:
pref.autoFitFullScreen = "fitGuestToHost"

but when i do it the preferences file is empty
Can anyone tell me where it is??
Totally lost
edit
I have installed VMtools...

A: The preference file is located on your host computer NOT in your VM!
Location on a Windows host:
C:\Users\<username>\AppData\Roaming\VMware\preferences.ini

Location on a Linux host:
~/vmware/preferences/preferences

A: I tested that, when Windows is guest OS, but may work with other OS too:

A: You need to install VMWare tools in order for your VM to make use of your screen resolution.
Follow this guide/tutorial in order to install it on vmware player.


text:
Q: Gender (and other additional claims) missing from OAuthCreatingTicketContext I have my Google Authentication provider configured like this:
.AddGoogle(options =>
                {
                    options.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo";

                    options.Scope.Add("https://www.googleapis.com/auth/user.phonenumbers.read");
                    options.Scope.Add("https://www.googleapis.com/auth/user.gender.read");
                    options.Scope.Add("https://www.googleapis.com/auth/user.birthday.read");
                    options.Scope.Add("https://www.googleapis.com/auth/user.addresses.read");
                    options.ClaimActions.MapAll();

                    options.SignInScheme = "google.identity";

                    options.ClientId = "REDACTED";
                    options.ClientSecret = "REDACTED";

                    options.Events.OnCreatingTicket = (context) =>
                    {
                        var gender = context.User.GetProperty("gender").GetString(); // Throws KeyNotFoundException
                        return Task.CompletedTask;
                    };
                });

But attempting to get the gender property throws a KeyNotFoundException.
I have checked with my test application and it does request the correct scopes

It's important to note that I am debugging this locally (via HTTPS)

A: The claims returned by the Google Authorization server are extremely limited.  You will not get things like gender info from that.  In order to get the gender for a user serval things need to happen.  First the user needs to have it set. Under their profile

Then you need to authorize the user with the following scopes yes both.
https://www.googleapis.com/auth/user.gender.read
https://www.googleapis.com/auth/userinfo.profile

Only then will you see the gender information for the user.
Example
Then you just need to make a request to the people api to get the users profile information.
[GoogleScopedAuthorize(PeopleServiceService.ScopeConstants.UserinfoProfile,PeopleServiceService.ScopeConstants.UserGenderRead)]
 public async Task UserProfile([FromServices] IGoogleAuthProvider auth)
        {
            var cred = await auth.GetCredentialAsync();
            var service = new PeopleServiceService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = cred
                });

            var request = service.People.Get("people/me");
            request.PersonFields = "gender";
            var person = await request.ExecuteAsync();

            return View(person);
        }


text:
Q: Creating varying number of parameters in an object by dynamically assigning their name? How would I write a procedure that would build this array such that I could choose as many parameter names such as KBP? I wanted?
public var expenses:ArrayCollection = new ArrayCollection([
    {Impact:"A", KBP1:1, KBP2:0, KBP3:0, KBP4:0 },
    {Impact:"B", KBP1:0, KBP2:0, KBP3:0, KBP4:0 },
    {Impact:"C", KBP1:0, KBP2:2, KBP3:3, KBP4:0 },
    {Impact:"D", KBP1:0, KBP2:0, KBP3:0, KBP4:8 },
    {Impact:"E", KBP1:0, KBP2:0, KBP3:0, KBP4:0 }
]);

A: Something like the following:
var arrayLength:int = 100;
var kbpsLength:int = 50;
var expensesArray:Array = [];
for (var i:int = 0; i < arrayLength; i ++)
{
    var item:Object = {Impact:"A"};
    for (var j:int = 0; j < kbpsLength; j ++)
    {
        item["KBP" + (j + 1)] = 0;
    }
    expensesArray.push(item);
}
var expenses:ArrayCollection = new ArrayCollection(expensesArray);

A: This is my understanding of your question. If this isn't what you're looking for, feel free to clarify.
var expenses:ArrayCollection = new ArrayCollection();

(loop conditions?)
{
    var item:Object = {};
    item.Impact = "A";
    item.KBP1 = 0;
    item.KBP2 = 0;
    item.KBP3 = 0;
    item.KBP4 = 0;
    item.KBP5 = 0;
    ...

    expenses.addItem(item)
}


text:
Q: Can we open mysql connection from a servlet ? (using mysql connector) I have a DatabaseConnectionOpen.java class as follows :
package db;

import java.sql.*;
public class DatabaseConnectionOpen {

static String dbHost = "jdbc:mysql://localhost:3306/javaweb?useSSL=false";
static String dbUsername = "user";
static String dbPassword = "user";

static Connection myConn = null;
static Statement myStmt = null;
static ResultSet myRes = null;

public void openConnection(){
    try {
        myConn = DriverManager.getConnection(dbHost, dbUsername, dbPassword);
    }
    catch (SQLException e) {
        e.printStackTrace();
    }
}
public ResultSet runQuery(String query){
    try{
        myStmt = myConn.createStatement();
        myRes = myStmt.executeQuery(query);
    }
    catch (SQLException e) {
        e.printStackTrace();
    }
    finally {
        return myRes;
    }
}
public void closeConnection(){
    try {
        if (myRes != null) myRes.close();
        if (myStmt != null) myStmt.close();
        if (myConn != null) myConn.close();
    }
    catch (SQLException e) {
        e.printStackTrace();
    }
}
}

It works fine when I use it from a class named ViewUsers.java whose code is as follows :
package dbImplement;

import db.DatabaseConnectionOpen;

import java.sql.ResultSet;
import java.sql.SQLException;

public class ViewUsers {

public static void main(String[] args) {

    ResultSet myRes = null;

    DatabaseConnectionOpen dbObject = new DatabaseConnectionOpen();

    dbObject.openConnection();

    try {
        myRes = dbObject.runQuery("SELECT * FROM users");
        while (myRes.next()) {
            System.out.println(myRes.getString("fname") + " " + myRes.getString("lname"));
        }
        myRes = dbObject.runQuery("SELECT * FROM users");
        while (myRes.next()) {
            System.out.println(myRes.getString("fname"));
        }
    }
    catch (SQLException e) {
        e.printStackTrace();
    }
    finally {
        dbObject.closeConnection();
    }

    dbObject.closeConnection();

}
}

But the problem occurs when I want to use DatabaseConnectionOpen.java from a servlet , code as follows :
package servlets;

import db.DatabaseConnectionOpen;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "FirstServlet", urlPatterns = {"/msg"})

public class FirstServlet extends HttpServlet {

protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    ResultSet myRes = null;
    DatabaseConnectionOpen dbObject = new DatabaseConnectionOpen();
    dbObject.openConnection();
    out.println("
Hello Sevlet
");

    try {
        myRes = dbObject.runQuery("SELECT * FROM users");
        while (myRes.next()) {
            out.println("
"+myRes.getString("fname") + " " + myRes.getString("lname")+"
");
        }
    }
    catch (SQLException e) {
        e.printStackTrace();
    }
    finally {
        dbObject.closeConnection();
    }

    dbObject.closeConnection();

}
}

It only prints "Hello Servlet" but not the h3 part, and says :
> java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/javaweb?useSSL=false
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at db.DatabaseConnectionOpen.runQuery(DatabaseConnectionOpen.java:28)
    at servlets.FirstServlet.doGet(FirstServlet.java:30)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Feb 16, 2017 2:14:30 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /opt/tomcat/webapps/manager
Feb 16, 2017 2:14:30 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deployment of web application directory /opt/tomcat/webapps/manager has finished in 100 ms

It say no driver found but i have the external libraries of mysql connector and my other class(ViewUsers.java) works fine at the same time but not the Servlet.


text:
Q: Elegant way to convert an array by subitems key I have this array:
array (size=3)
  0 =>
    array (size=2)
      'name' => string 'XML' (length=3)
      'processer' => string 'XMLp' (length=12)
  1 =>
    array (size=2)
      'name' => string 'XML2' (length=3)
      'processer' => string 'XML2pr' (length=12)
  2 =>
    array (size=2)
      'name' => string 'CSV' (length=3)
      'processer' => string 'CSVp' (length=12)

Since I dont need all of this, I wasnt this array converted:
$a = array ('XML', 'XML2', 'CSV');

so get by 'name'. How to do this elegantly in php?

A: $source = array(
    0 => array (
        'name' =>'A',
        'processer' => 'XMLf'),
    1 => array (
            'name' =>'B',
            'processer' => 'XMLp'),
    2 => array (
            'name' =>'C',
            'processer' => 'XMLp')
);

$output = array_map(function ($value) {
    return $value['name'];
}, $source);

print_r($output);

A: You could just loop over it, I don't think there's a much more elegant way:
$a = array();
foreach ($array as $value) {
    $a[] = $value ['name'];
}

A: foreach($array as $a) $new[] = $a['name'];


text:
Q: Formatting y-axis How can I format monetary values of the y-axis of my graph bar to be so:
R$ 123.456,00

Instead of:
R$ 123,456.00

Currently I'm using this function to format, but can't make this simple change:
var format = d3.format(',.2f'); // Need to change this, but don't know how

chart.yAxis.tickFormat(function(d) {
    return "R$ " + format(d);
});

I've already searched in D3 documentation, but can't find anything.

A: With d3 5.5 you can create a custom locale
https://github.com/d3/d3-format#formatLocale
Also note in the specifier(arg passed to .format) I now include a $ This will automatically include the currency prefix in the formatted string.
const customD3Locale = d3.formatLocale({
  decimal: ",",
  thousands: ".",
  grouping: [3],
  currency: ["R$",""]
})

const format = customD3Locale.format('$,.2f');

A: The format method don't seems to allow custom thousands and decimal separators. I think that you should replace the symbols yourself:
var format = d3.format(',.2f');

// Format the number, adding thousands and decimal separators
var label = format(1234.00);

// Replace the . and the , symbols. The ! symbol is necessary to do the swap
// it can be other symbol though
label = label.replace('.', '!');
label = label.replace(',', '.');
label = label.replace('!', ',');

// The result is 'R$ 1.234,00'
d3.select('#chart').append('p').text('R$ ' + label);

This jsfiddle have the replacement code.


text:
Q: OpenOCD and stm32 My system: Windows 8, USB 3.0 ports.
I want to debug my stm32f7-disco  in ChibiStudio. After build I try to connect using OpenOCD and ST-Link, but get the following:
Open On-Chip Debugger 0.10.0+dev-00161-g1725abc3c (2017-06-24-20:22)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 2000 kHz
adapter_nsrst_delay: 100
srst_only separate srst_nogate srst_open_drain connect_deassert_srst
Info : Unable to match requested speed 2000 kHz, using 1800 kHz
Info : Unable to match requested speed 2000 kHz, using 1800 kHz
Info : clock speed 1800 kHz
Error: libusb_open() failed with LIBUSB_ERROR_NOT_SUPPORTED
Info : STLINK v2 JTAG v27 API v2 SWIM v15 VID 0x0483 PID 0x374B
Info : using stlink api v2
Info : Target voltage: 3.224704
Warn : Silicon bug: single stepping will enter pending exception handler!
Info : stm32f7x.cpu: hardware has 8 breakpoints, 4 watchpoints

I think problem in libusb and usb 3.0.


text:
Q: Loading SPIRV binary shader fails In my program I tried to load precompiled binary shaders with the example code from Sasha Willems (https://github.com/SaschaWillems/openglcpp/blob/master/SPIRVShader/main.cpp):
bool loadBinaryShader(const char *fileName, GLuint stage, GLuint binaryFormat, GLuint &shader)
{
    std::ifstream shaderFile;
    shaderFile.open(fileName, std::ios::binary | std::ios::ate);
    if (shaderFile.is_open())
    {
        size_t size = shaderFile.tellg();
        shaderFile.seekg(0, std::ios::beg);
        char* bin = new char[size];
        shaderFile.read(bin, size);

        GLint status;
        shader = glCreateShader(stage);                                 // Create a new shader
        glShaderBinary(1, &shader, binaryFormat, bin, size);            // Load the binary shader file
        glSpecializeShaderARB(shader, "main", 0, nullptr, nullptr);     // Set main entry point (required, no specialization used in this example)
        glGetShaderiv(shader, GL_COMPILE_STATUS, &status);              // Check compilation status
        return status;
    }
    else
    {
        std::cerr << "Could not open \"" << fileName << "\"" << std::endl;
        return false;
    }
}

I have created the following two simple shaders for testing:
test.frag
#version 450

in vec4 color;
out vec4 outCol;
void main()
{
    outCol = vec4(1., 0., 0., 1.);
}

and text.vert
#version 450

layout (location = 0) in vec3 inPos;
layout (location = 1) in vec3 inColor;

layout (location = 0) out vec3 outColor;

out gl_PerVertex
{
    vec4 gl_Position;
};

void main()
{
    outColor = vec3(0.2, 1., 0.2);
    gl_Position = vec4(5.*inPos.xyz, 1.0);
}

I converted them to SPIR-V format with glslangValidator from github:
https://github.com/KhronosGroup/glslang
I used:
glslangValidator.exe test.vert -G -o anypath.spv

When I'm trying to load these shaders, it crashes with an segmentation fault at line
glSpecializeShaderARB(shader, "main", 0, nullptr, nullptr);

I've tried the same on another PC with an older GPU (GeForce GTX 660) and it just works fine. But it doesn't work on my new PC with the Radeon R9 Fury X.
Any Ideas?


text:
Q: Wordpress installation shows in plain html I'm trying to install wordpress on a VPS. Created database, mysql user, unzipped wp file. All the usual.. works everywhere else, but on my new VPS it shows as plain HTML.
If I proceed, the installation is successful, but then the site can't function properly. http://i.imgur.com/ltwlaRL.png
What could be the issue? Thank you!


text:
Q: Map transformation to apply a new path on a list of strings which are urls I have a list of strings (newsFeeds) which are a links. Some of them have a path component and some of them not. My goal is to apply a custom path component only when a path component is present. My code is below.
How to write it in more Kotlin style?
newsRepository.getAllNewsFeeds().observeForever { newsFeeds ->

    listNewsFeedUrls = newsFeeds.mapNotNull { newsFeed ->

        if (newsFeed.newsfeedURL?.toUri()?.path.isNullOrEmpty()) {
            newsFeed.newsfeedURL + "/us/json/news"
        } else {
            newsFeed.newsfeedURL
        }
    }

}

A: Your code already looks good. Don't decrease readability for the sake of making it more Kotlinish.
If you still want to see another way, take a look at this:
If you want to avoid redundancy you could map you list of newsFeeds to a list of newsfeedURLs right away. Additionally you can concatenate either a path or an empty string to avoid having to reference url twice.
newsFeeds.mapNotNull(NewsFeed::newsfeedURL).map { url ->

     url.toString() + if (url.toUri()?.path.isNullOrEmpty()) {
        "/us/json/news"
    } else {
        ""
    }
}

A: What you've written it is already pretty Kotlinish. You can also use such functions as filter, zip, for example:
val result = newsFeeds.filter { it.newsfeedURL != null && it.newsfeedURL.toUri().path.isNullOrEmpty()}
            .map { "${it.newsfeedURL}/us/json/news" }
            .zip(newsFeeds.filter { it.newsfeedURL != null && !it.newsfeedURL.toUri().path.isNullOrEmpty() })


text:
Q: Как понять какой view был обновлен? Eсть scrollview, внутри Linearlayout, а внутри Linearlayout динамически создаются(добавляются) view разного типа(edittext, spinner, date...) и заполняются данными, у всех enable(false).
Нажимаем edit, меняем например инфу одного из edittext и date.
Вопрос, как правильно определить, инфо какой именно view был обновлен?

A: Можно использовать двойной databinging. Тогда данные, которые устаналиваюся во View-их, по завершении экрана будут стянуты в объекты. А объеты уже можно сравнить. Попробуйте вот эту статью https://habr.com/post/260317/ по обратной свяи.


text:
Q: Object pool of singleton-like objects I have written an implementation of a pool of singleton-like immutable objects ("singleton" in the sense that I only need one copy of each object with the same field values) as follows. I don't like the fact that I have to create the object only in order to check if I already have an equivalent object in the pool. Is there a way to avoid that? (i.e. check if I already have the object I need in the pool and only create it if it's not there).
Note: different child classes can have multiple different fields or no fields at all.
public class Parent {
    protected static final Map<Parent, WeakReference<Parent>> pool = Collections.synchronizedMap(new WeakHashMap<>());
}

public class Child extends Parent
{
    final int field1;
    final int field2;

    private Child(int field1, int field2) {
        this.field1 = field1;
        this.field2 = field2;
    }

    public static Child newChildClass(int field1, int field2) {

        Child child = new Child(field1, field2);
        Child obj = (Child)pool.get(child).get();
        if (obj == null) pool.put(obj = child, new WeakReference<>(child));
        return obj;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Child that = (Child) o;
        return field1 == that.field1 && field2 == that.field2;
    }

    @Override
    public int hashCode() {
        return Objects.hash(getClass(), field1, field2);
    }
}

A: Can you leverage a nested HashMap on the fields seeing as they are both of type int?
Map<Integer, Map<Integer, Parent>> pool = new HashMap<>();

You can then have a method to see if a cached singleton exists (I didn't have an IDE at the time so please bear with me on some syntax errors / bugs):
public Child getChild(int field1, int field2) {
    Map<Integer, Parent> nestedMap = pool.get(field1);

    if (nestedMap == null) {
        // Child doesn't exist, create map
        nestedMap = new HashMap<>();
    }

    if (nestedMap.contains(field2)) {
        // cached child found, return it
        return nestedMap.get(field2);
    } else {
        // cached child doesn't exist, create and return it
        Child child = newChildClass(field1, field2);
        nestedMap.put(field2, child);
        pool.put(field1, nestedMap);
        return child;
    }
}

A: Your pool map's key must be changed to something else. I would try making a hash of the child object's fields and use it as the key. So when I have to check for the existence of a child with those fields I only need to calculate the hash of the fields and lookup for it in the pool.
I agree with your comment on hash code's uniqueness. Or you can convert fields to Strings and append field values to make up a unique string to be used as key:
static final String fieldSeparator = "somevalue";
String uniqueKey = fieldSeparator + field1.toString() + fieldSeparator + field2.toString() + ....
The idea is to make a unique key out of the fields.


text:
Q: Javascript radiobutton value in variable I trying to write a small script, which checks if the verb match one of the 3 groups.
So:

*

*Making new array with verbs

*Random selection of the verb from array.

*User vote for the group, selected verb removed from array.

*Next, etc.

Looping & ifing not a problem, but I've never worked with radio buttons.
So at the moment I have the following:

window.onload = function () {
 var verb_array = new Array (1,2,3)
 var random_verb_array_num = Math.floor(Math.random() * (verb_array.length - 0+0)) + 0;
 var random_verb_array_value = verb_array[random_verb_array_num];
 var show = document.getElementById("wuza").innerHTML = random_verb_array_value;
 verb_array.splice(random_verb_array_num, 1);
}

<form action="">
 <input type="radio" name="group" value="1">1 Group
 <input type="radio" name="group" value="2">2 Group
 <input type="radio" name="group" value="3">3 Group

<input type="submit" value="Check" />
</form>

I need to create a new variable in my function, e.g. radio_value, and write there user's value after checking radio and pressing submit. How can I do that?

A: You need to create a new function for when the submit button is clicked that takes the form information and communicates what you're looking for, like so:

<form action="">
 <input type="radio" name="group" value="1" onClick="userChoice(1);">1 Group
 <input type="radio" name="group" value="2" onClick="userChoice(2);">2 Group
 <input type="radio" name="group" value="3" onClick="userChoice(3);">3 Group

<input type="button" value="Check" onClick="alert('The user submitted ' + userDecided);" />
</form>

You'll need some sort of asynchronous loading though. I wrote the code in such a way so that you can initialize some further instructions based on the user's selection.
For DEBUGGING purposes, upon clicking the submit button, I have an alert display which choice was made to further your understanding.


text: Q: Необходимо реализовать переключение между фотографиями товара на сайте Пишу магазин на django python, на странице данного товара хочу сделать систему, при которой после клика на конкретное изображение оно выводилось как главное. Понимаю, что скорее всего здесь необходим JS, но на нём никогда не работал. Помогите пожалуйста, вдруг есть готовые решения.


text:
Q: Orthogonal Projections Are Symmetric - Geometric Intuition Let us denote the projection matrix onto the column space of $A$ by $\pi_A = A(A^T A)^{-1} A^T$. I am looking for geometric intuition as to why it is symmetric. It is very clear to me due to plenty of algebraic reasons (taking transpose, showing $\left \langle \pi_A u,v \right \rangle=\left \langle u,\pi_A v \right \rangle$ and so on...), but I am looking for something of the sort of "proof without words" which could be explained with pictures.
For example, it is clear to me that $\pi_A^2=\pi_A$, since projecting a vector which is already in $\text{col}(A)$ onto $\text{col}(A)$, is itself. Same goes to show $\pi_A A = A$.
I saw many posts addressing this problem, however all the explanations I read resorted to over-killing with calculations.

A: Here's an idea you might like.  Suppose that $P$ is a projection matrix. That is, $P^2 = P$ but $P$ is not necessarily symmetric. In other words, $P$ is "the projection onto $\operatorname{im}(P)$ along $\ker(P)$".  The transpose $P^T$ is another projection; you can verify (by various means) that $P^T$ represents "the projection onto $\ker (P)^\perp$ along $\operatorname{im}(P)^\perp$."
The only time these projections are the same is when $\ker (P) = \operatorname{im}(P)^\perp$. That is, $P$ and $P^T$ can only be the same if $P$ is the orthogonal projection onto $\operatorname{im}(P)$.

We can see that $Q = P^T$ must be the projection onto $\ker (P)^\perp$ along $\operatorname{im}(P)^\perp$ as follows. Note that any vector $x$ can be decomposed into $x = x_{im} + x_{\ker}$, where $x_{im} = Px$ and $x_{\ker} = x-Px$.
For any vector $y \in \ker(P)^\perp$ and any $x$, we have
$$
\langle y, x\rangle = \langle y, x_{im} + x_{\ker} \rangle = \langle y, x_{im} \rangle = \langle y, Px \rangle = \langle Qy,x \rangle.
$$
So, $Qy = y$. Similarly, we can show that $Qy = 0$ for $y \in \operatorname{im}(P)^\perp$.

A: First let's understand why $\langle x,\pi_Ay\rangle=\langle \pi_A x,\pi_Ay\rangle$. The point is that because $\pi_Ay$ is in the subspace spanned $A$, its inner product with $x$ only "sees" the components of $x$ that lie in that subspace because the components that are orthogonal to it will give an inner product of $0$. More formally, we can write $x= \pi_A x + (x-\pi_A x)$ where the latter term is orthogonal to the subspace (you may check this easily) from which the claim follows by the linearity of the inner product:
$$\langle x,\pi_Ay\rangle= \langle \pi_Ax+(x-\pi_Ax),\pi_Ay\rangle=\langle \pi_Ax,\pi_Ay\rangle+\langle x-\pi_Ax,\pi_Ay\rangle=\langle \pi_A x,\pi_Ay\rangle$$
With this in mind, it makes sense that it shouldn't matter if we project $x$ to the span of $A$ first or project $y$ first before taking the inner product, because we are only taking the product "relative to the components in the span of $A$." And this statement about which process we've done first is exactly the statement that $\langle x,\pi_Ay\rangle=\langle \pi_A x,y \rangle$.

A: The orthogonal projection $Px$ of a vector $x$ onto a subspace $M$, is the unique $m\in M$ such that $(x-m)\perp M$. This is equivalent to
$$
        \langle x-Px,Py\rangle = 0,\;\;\; x,y\in H, \\
         \langle x,Py\rangle=\langle Px,Py\rangle
$$
Therefore, $\langle x,Py\rangle = \langle Px,Py\rangle$ is symmetric.


text:
Q: Access violation on reading location 0x33313032. when build the project under x86 platform the ame works fine under 64bit platform Im getting this error when i run my dualcore project with build set to x86 platform on vs2010
Unhandled exception at 0x6711b1a5 in dualcore.exe: 0xC0000005: Access violation reading location 0x33313032.
and the application breaks.
when checked on windows event logger it specified the following "Application error" and the "runtime error":
Application error :
Faulting application name: Dual OS.exe, version: 1.0.0.1, time stamp: 0x51b742ba
Faulting module name: MSVCR100.dll, version: 10.0.30319.460, time stamp: 0x4db13576
Exception code: 0xc0000005
Fault offset: 0x0007b1a5
Faulting process id: 0x13b4
Faulting application start time: 0x01ce68c896a83d38
Faulting application path: C:\Program Files\Samsung\Dual OS\Dual OS.exe
Faulting module path: C:\Windows\SYSTEM32\MSVCR100.dll
Report Id: ed3658bb-d4bb-11e2-a5e2-3860772fed6d
Faulting package full name:
Faulting package-relative application ID:
Runtime error:
Application: dualcore.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
   at ._wWinMainCRTStartup()
The same project works fine when built under x64 bit.
I need the same 32bit also
kindly help me out to solve this!.

A: Number 0x33313032 is very suspicious. Those are actually letters "3" "1" "0" "2". Somewhere in your code you have those letters in the memory, and the code thinks that that part of memory is some pointer instead of those four letters, and is trying to reach where the pointer points, which is 0x33313032.


text:
Q: jQuery UI Autocomplete - setting source after _create/_init not working? According to the jQuery UI, you should set the autocomplete source after create/init as follows:
$( ".selector" ).autocomplete( "option", "source", ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] );
Here is some of the code (based off of the combobox  example):
     $("#item").combobox();
     $("#item").autocomplete("option", "source", function (request, response) {
         $.ajax({
             type: "POST",
             url: "itmsrch.ashx",
             dataType: "json",
             data: {
                 dept: $("#dept").val,
                 term: request.term
             },
             success: function (data) {
                 response($.map(data, function (item) {
                     return {
                         label: item.name,
                         value: item.name
                     }
                 }));
             }
         });
     });

After typing the required 2 characters to kick off the autocomplete action, I am getting an error that the source is not set.  Any ideas?

A: The reason this won't work is that the combobox sample actually creates an input and applies the autocomplete widget to it and not the select that you called combobox() on:
/* Snip */
var input = this.input = $( "<input>" )
    .insertAfter( select )
    .val( value )
    .autocomplete({ ... });
/* Snip */

In order to modify the source of combobox's internal autocomplete, you could write:
$("#combobox").next("input").autocomplete("option", "source", ["Foo", "Bar"]);

Or, more generally, you could add the following to the plugin:
_setOption: function(key, value) {
    this.input.data("autocomplete")._setOption(key, value);
}

And then modify autocomplete options using:
$("#item").combobox("option", "source", ["Foo", "Bar"]);

I'd recommend this method.
However, this will cause issues because the combobox code's event handler for the autocomplete's select expects that the selected item has an option property (check out the source code).  Additionally, this will break any event handlers you have on the select (e.g. change).
If you don't care about updating the underlying select (which I bet you don't since you're changing the datasource), you can remove the select event handler entirely.
I have a working example here that uses the last method and seems to work okay.


text:
Q: LWJGL Collision Detection flaw I am currently using this code for 2D Collision Detection in my Space Invaders like game :
for(byte k = 0; k < enemies.length; k++) {
    if(shot.x < enemies[k].getTexture().getImageWidth() && shot.x  > enemies[k].pos.x) {
            if(shot.y - 1.2f * frameCount < enemies[k].pos.y && shot.y - 1.2f * frameCount > Main.enemies[k].pos.y - enemies[k].getTexture().getTextureHeight()) {
                    Main.enemies[k].hit = true;
            }
    }
}

However, there is one major flaw in this type of collision detection; I can only detect collisions coming form below. Why is this?

A: The reason you are only getting collisions from the bottom is that
your bounds checking has some errors.
Below I have given a fixed and slightly clearer version,
and I assume that shotWidth and shotHeight can be calculated.
(I have left out the part regarding frameCount, but it should
be possible to edit it in again if needed).
final int shotX = shot.x;
final int shotY = shot.y;
final int shotWidth = ?
final int shotHeight = ?
for(byte k = 0; k < enemies.length; k++) {
    final int enemyX = enemies[k].pos.x;
    final int enemyY = enemies[k].pos.y;
    final int enemyWidth = enemies[k].getTexture().getImageWidth();
    final int enemyHeight = enemies[k].getTexture().getImageHeight();

    if(     shotX < enemyX + enemyWidth &&
            shotX + shotWidth < enemyX &&

            shotY < enemyY + enemyHeight &&
            shotY + shotHeight < enemyY) {

        Main.enemies[k].hit = true;
    }
}


text:
Q: Is there a pause shorter than a comma? I'm writing a poem, and like how it's flowing. But I find that a tiny pause shorter than a comma would do tremendous. Is there such a mark or multitude of symbols to make a short pause?

A: I really believe
You should use
Line breaks
To give people
A chance
To think.
Maybe  you could use multiple spaces?

A: Depending on your poetic style, you can add a syllable to a word to increase the length of the sentence or line. However, it's poetry; that probably won't work. But because it's poetry, there's nothing against using two or more spaces after a word. The reader will automatically slow down if for nothing else because it's unusual.

A: Semicolons and colons have been relegated to the fringes more and more in the last hundred years. A comma seemed relatively short in the old days, but now it can seem oppressive. An unintended consequence of the continuing distaste for periodic writing.


text:
Q: Как мне сделать проверку ввел ли пользователь число, а не текст Как мне сделать проверку ввел ли пользователь число, а не текст ( код там где я ввожу degrees или вторая try/catch ) и пользователь должен вводить до тех пор пока не введет число.
Code:
import java.util.Scanner;

public class main {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);

        int numbers;
        int degrees;
        int exit ;
        System.out.print("Hello,");
        while (true){

            System.out.print(" write number  of type convert:   \n 1-Degrees Celsius To Fahrenheit \n 2-Degrees Fahrenheit To Celsius \n Number: ");

            try{
                numbers = cin.nextInt();
                while (true)
                    if(numbers != 1 | numbers != 2  ){

                        System.out.println("Write right number ( 1 or 2 )");
                        numbers = cin.nextInt();

                        if (numbers ==1 | numbers == 2){
                            break;
                        }

                    }
            }
            catch (Exception e){
                System.out.println("Please write number ,not text");
                numbers = cin.nextInt();

            }

            System.out.println("Write degrees: ");
            while (true){

                try{
                    degrees = cin.nextInt();

                }catch (Exception e){
                    System.out.println("Please write number,not text");
                    degrees = cin.nextInt();

                }
                break;

            }
        }
    }
}

A: Используйте hasNextInt() в условие while

A: После нескольких ответов на ru.SO у меня выбработалось правило большого пальца:

Никогда не используйте nextInt (nextDouble, или другие next...)
в интерактивном вводе.

Считывайте строку целиком (nextLine()) и преобразуйте в к нужному типу (Integer.parseInt):
private static int readInt(Scanner s, String prompt) {
    while (true) {
        System.out.print(prompt);
        String line = s.nextLine();
        try {
            return Integer.parseInt(line);
        } catch (NumberFormatException e) {
            System.err.println("Error: wrong integer");
        }
    }
}

Чем плох nextInt? Тем что в случае ошибки, весь ошибочный текст остаётся в сканере так как будто чтения не было вообще. Если вы ещё раз вызовете nextInt, он снова попытается прочитать тот же мусор. У вас есть эта ошибка: при вводе неверных градусов программа зациклится навсегда. Мусор в случае ошибки нужно убирать вызовом next.
Если пользователь введёт несколько целых на одной строке ввода, nextInt считает первое число и передаст управление дальше. Если дальше есть ещё ввод он будет работать с остатком строки. Для пользователя это выглядит как то, что программа печатает приглашения на ввод, не даёт ввести данные и продолжает работу. Или позже сообщает об ошибках там где никакого ввода не было.


text:
Q: Assigning client certificates to users We are trying to authenticate users from a particular group with client certificates installed on their machines in addition to user credentials.
I followed the steps in this article - http://ondrej.wordpress.com/2010/01/24/iis-7-and-client-certificates/.
I still cannot see the client certificate being requested by the server or the client certificate being passed to the server even though the CA used to generate the client certificates is in Trusted Root certificate store on clients and server. The IIS on the server is configured to accept client certificates since not all users will have the certificates installed.
Do I need to do anything specific in .NET code on the server side to explicitly request the client certificate?


text:
Q: android native app opengl es white textures I'm writing a native app that should only display a little triangle with a texture.
But unfortunately, it everytime only displays a white triangle.
My code is very simple.
First to load a tga Image:
static const GLenum gl_format[4] = { GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RGB, GL_RGBA };

unsigned int LoadTGATextureFromFile(const char* filename)
{
    unsigned int handle;
    unsigned char hdr[18];
    unsigned char file_id[256 + 1];
    int file;

    file = open(filename, O_RDONLY);
    if(file < 0)
    {
        Log(LOGLEVEL_ERROR, APPNAME, "Error: Failed to open tga file '%s' for read ing\n", filename);
        return 0;
    }

    if(read(file, hdr, 18) != 18 || read(file, file_id, hdr[0]) != hdr[0])
    {
        Log(LOGLEVEL_ERROR, APPNAME, "Error: Unexpected EOF while reading header of '%s'\n", filename);
        close(file);
        return 0;
    }
    file_id[hdr[0]] = 0;
    if(hdr[1] != 0 || (hdr[2] != 2 && hdr[2] != 3) || (hdr[16] != 8 && hdr[16] != 16 && hdr[16] != 24 && hdr[16] != 32))
    {
        Log(LOGLEVEL_ERROR, APPNAME, "Error: File '%s' has invalid format\n", filename);
        close(file);
        return 0;
    }
    int width = *(short*)(hdr + 12);
    int height = *(short*)(hdr + 14);
    if((width & (width - 1)) != 0 || (height & (height - 1)) != 0)
    {
        Log(LOGLEVEL_ERROR, APPNAME, "Error: File '%s' has invalid resolution %dx%d\n", filename, width, height);
        close(file);
        return 0;
    }
    int components = hdr[16] / 8;

    unsigned char* data = new unsigned char [width * height * components];
    if (read(file, data, width * height * components) != width * height * components)
    {
        Log(LOGLEVEL_ERROR, APPNAME, "Error: Unexpected EOF while reading image data of '%s'\n", filename);
    close(file);
        return 0;
    }
    close(file);

    char dummy;
    if(read(file, &dummy, 1) == 1)
        Log(LOGLEVEL_ERROR, APPNAME, "Warning: TGA file '%s' has overlength\n", filename);

    switch (components - 1)
    {
        char tmp;
        case 2:
            for (int i = 0; i < width * height; i += 3)
            {
                tmp = data[i];
                data[i] = data[i + 2];
                data[i + 2] = tmp;
            }
            break;

        case 3:
            for (int i = 0; i < width * height; i += 4)
            {
                tmp = data[i];
                data[i] = data[i + 2];
                data[i + 2] = tmp;
            }
            break;

        default:
            break;
    }

    glGenTextures(1, &handle);
    glBindTexture(GL_TEXTURE_2D, handle);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glBindTexture(GL_TEXTURE_2D, 0);

    delete [] data;
    Log(LOGLEVEL_ERROR, APPNAME, "'%s' successfully loaded [handle = %d, FILE_ID = \"%s\", width = %d, height = %d, depth = %d] :)\n", filename, handle, file_id, width, height, components * 8);

    return handle;
}

Loading the texture:
int texture = LoadTextureFormFile("/sdcard/test.tga");

Then to draw:
    float tricoords[6] = { 0.0, 0.0, 1.0, 1.0, 0.0, 1.0 };
    float texcoords[6] = { 0.0, 0.0, 1.0, 1.0, 0.0, 1.0 };

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glVertexPointer(2, GL_FLOAT, 0, tricoords);
    glTexCoordPointer(2, GL_FLOAT, 0, texcoords);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

I know, that this code isnt optimized, but its only for debugging.
The logcat of my app prints:
 successfully loaded tga [handle = 1, FILE_ID = "", width = 64, height = 128, depth = 32] :)
But the texture stays white.

A: Just found the mistake, texture mipmapping was enabled for the loaded texture the mipmaps were never created.
Changing this line:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

to  this will disable mipmaps for the texture.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);


text:
Q: Remote Desktop over SSH SOCKS proxy to bypass firewall I'm trying to connect to a Windows server from my Mac using RDC2.1 for Mac.
The problem is the server I need to connect to is guarded by the evil dragon - IP-based access control on a completely separate network.
I have an IP I can get in on, but it's at my office (i.e. a completely separate network).
Because that network isn't set up for VPN, I've set up a SOCKS proxy through an SSH tunnel (which is all working fine).
               (SSH proxy)
Me (on my Mac) ----------> Office Linux box ----> Windows server
(home network)             (office network)       (other network)

From my Linux server in my office (the SSH server) I can telnet to port 3389 on the Windows server, no problem. But from my Mac I can't get so much as a squeak out of it. Any ideas?

A: You don't need a SOCKS proxy for this; simple SSH port forwarding will work.  For example, there's a server at my office I frequently need to access, which we'll call server.example.com.  I can't connect to it directly, but I can ssh to myofficemachine.example.com.  So I do this:
ssh -L 3389:server.example.com:3389 myofficemachine.example.com

And then I point my local Remote Desktop client to localhost. This works great, and my setup is almost identical to yours -- a Mac at home, a Linux box at my office, and a Windows server on another work network.

A: You could try using CoRD, a replacement remote desktop app which supports SOCKS proxies.


text:
Q: Error install pg gem I am getting the following error when trying to install 'pg' Any thoughts? I am pretty new to rails so I am not sure how to fix this issue.
Davids-MacBook-Air:~ DavidStevenson$ install pg
usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
               [-o owner] file1 file2
       install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
               [-o owner] file1 ... fileN directory
       install -d [-v] [-g group] [-m mode] [-o owner] directory ...
Davids-MacBook-Air:~ DavidStevenson$ gem install pg
Building native extensions.  This could take a while...
ERROR:  Error installing pg:
    ERROR: Failed to build gem native extension.

    /usr/local/rvm/rubies/ruby-1.9.3-p392/bin/ruby extconf.rb

make
compiling gvl_wrappers.c
compiling pg.c
pg.c: In function 'Init_pg_ext':
pg.c:384: error: 'PQPING_OK' undeclared (first use in this function)
pg.c:384: error: (Each undeclared identifier is reported only once
pg.c:384: error: for each function it appears in.)
pg.c:386: error: 'PQPING_REJECT' undeclared (first use in this function)
pg.c:388: error: 'PQPING_NO_RESPONSE' undeclared (first use in this function)
pg.c:390: error: 'PQPING_NO_ATTEMPT' undeclared (first use in this function)
make: *** [pg.o] Error 1

Gem files will remain installed in /usr/local/rvm/gems/ruby-1.9.3-p392/gems/pg-0.15.1     for inspection.
Results logged to /usr/local/rvm/gems/ruby-1.9.3-p392/gems/pg-0.15.1/ext/gem_make.out

A: You probably need to install the postgresql development libraries first, using one of (homebrew, macports, fink). I personally still like macports, but homebrew seems to be growing more popular. If that still doesn't work, you may need to pass some flags to the 'gem install' command to tell it where to find those libraries.

A: please try following link install postgres on Mac :
how to install postgresql for mac os x
Installing Postgresql on Mac Lion


text:
Q: Could my website being UTF-8, and database being Latin1, cause Insert errors? I am just trying to see if this is the reason for a recent bug:
Values in a certain table are sometimes NOT inserted properly, this seems to have arisen after a change I made to the text-encoding on this website, from ISO-8859-1 to UTF-8 because of text display errors on the website itself. At the time, I did not know this could cause DB errors, but the DB is encoded in Latin1 which I believe is the same as ISO-8859-1.
Could the page with forms, being UTF-8, trying to inserts into a Latin1 db, cause a HARD insertion error for certain queries -- that is, the query fails entirely, as opposed to entering in strange character strings due to encoding mismatch?
EDIT -- I am asking because I cannot myself replicate the insertion bug, I can only observe that it has happened twice to other users. These users do not seem to use special characters in their registration, which adds to the confusion...
Thank you sincerely for your help and time,
-H


text:
Q: Submit stops working after first successful submit I have a simple form in a rails app that is rendered within a partial called roster_panel:

  <%= semantic_form_for @roster_item do |form| %>

Add a counselor

<%= @status_message %>

      <%= form.inputs do %>
          <%= form.input :first_name, input_html: {id: 'counselor_first_name'} %>
          <%= form.input :last_name, input_html: {id: 'counselor_last_name'} %>
          <%= form.input :email, input_html: {id: 'counselor_email'} %>

        <input id="submit_counselor_add" type="button" value = "Send forms packet" class = "button" >

      <% end %>
  <% end %>

In my jquery code, I tie the submit click to this:
$( document ).on('turbolinks:load', function() {
    $("#submit_counselor_add").click(function(){
        $.get("add_counselor_info" , { id: $("#roster_id").text(), first_name: $("#counselor_first_name").val(),
                last_name: $("#counselor_last_name").val(), counselor_email: $("#counselor_email").val() },
            function(data){ $("#roster_panel").html(data);
            }
        )
    });
});

This routes to this controller method:
def add_counselor_info
  @roster = Roster.find(params[:id])
  @group = ScheduledGroup.find(@roster.group_id)
  @liaison = Liaison.find(@group.liaison_id)
  @items = RosterItem.where(roster_id: @roster.id)
  @roster_item = RosterItem.new(group_id: @group.id, roster_id: @roster.id,
                                first_name: params[:first_name], last_name: params[:last_name],
                                email: params[:counselor_email], youth: false, item_status: 'Unconfirmed' )
  if @roster_item.save
    @error_count = 0
    @status_message = 'This counselor has been added and the forms package has been emailed. You may enter another counselor.'
    @items = RosterItem.where(roster_id: @roster.id)
    @roster_item = RosterItem.new
  else
    @error_count = @roster_item.errors.size
    @status_message = "#{@error_count} errors prevented saving this information: "
    @roster_item.errors.full_messages.each { | message | @status_message << message << ' '}
    @items = RosterItem.where(roster_id: @roster.id)
  end
  render partial: 'roster_panel'

end
After a fresh page load, this process works fine and redisplays the form as expected. However, at that point the submit button no longer triggers the action in jquery. Other jquery functions on the page still work, however. This may have something to do with turbolinks, which I am not very familiar with.
Any help would be appreciated!

A: After submitting the form, the DOM is replaced by the new one, so on click event binding is being lost.
Try to bind this event through the parent element, which won't be overridden by javascript (e.g. body):
$( document ).on('turbolinks:load', function() {
  $("body").on('click', '#submit_counselor_add', function() {
    $.get("add_counselor_info", {
      id: $("#roster_id").text(),
      first_name: $("#counselor_first_name").val(),
      last_name: $("#counselor_last_name").val(),
      counselor_email: $("#counselor_email").val()
    },function(data) {
      $("#roster_panel").html(data);
    });
  });
});


text:
Q: javascript comparison crises I came across the following and was unable to grasp the reason, can anyone explain please?
var foo = [0];
console.log(foo == !foo); // true
console.log(foo == foo);  // true

A: The second comparison is simple to explain: foo is equal to itself.
The first one, however, is a bit tricky: foo is an array, which is an object, which evaluates to true when coerced to boolean. So !foo is false. But foo on the left side of the comparison is not being converted to boolean. Both operands are actually converted to numbers during the equality comparison. This is how it evaluates:
[0] == false
[0] == 0
"0" == 0
0 == 0
true

According to MDN, on comparisons with the equality operator ==:

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible

I know this explanation sounds superficial. It's actually much more complicated than that, but the basic steps are the ones I listed above. You can see the details on the ECMA-262 specification, particularly on sections 9 and 11.9.

A: You should use "===" and "!==" instead of "==" and "!="
More explanations there:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
http://net.tutsplus.com/tutorials/javascript-ajax/the-10-javascript-mistakes-youre-making/


text:
Q: gcloud docker registry filter by timestamp I'm trying to find images older than some date using the gcloud sdk. I tried
gcloud container images list-tags gcr.io/my-project/my-image --filter='timestamp < 2017-07-01'
but this gives me all images, so the filter doesn't work.

A: Well, that one was easier than I initially thought. This is the solution:
gcloud container images list-tags gcr.io/my-project/my-image --filter='timestamp.datetime < 2017-07-01'
--format=json showed me the right fieldname.

A: Another way of doing and letting you select which field values you want to obtain:
gcloud container images list-tags \
  --quiet --project "${PROJECT}" "gcr.io/${PROJECT}/${IMAGE_NAME}" \
  --sort-by="~timestamp" --format='get(digest)' \
  --filter="timestamp.datetime < 2021-10-29"

And to avoid the confusing gcloud warning WARNING: The following filter keys were not present in any resource : timestamp.datetime, you can use this condition:
if [[ $(gcloud container images list-tags --project "${PROJECT}" "gcr.io/${PROJECT}/${IMAGE_NAME}" --format='get(digest)' | wc -l) -gt 0 ]]; then
    gcloud container images list-tags \
      --quiet --project "${PROJECT}" "gcr.io/${PROJECT}/${IMAGE_NAME}" \
      --sort-by="~timestamp" --format='get(digest)' \
      --filter="timestamp.datetime < 2021-10-29"
fi


text:
Q: How to config Eclipse select world Please help me how to change this yellow background color in eclipse. Thanks you!

A: Right click > Preferences > Editor
and choose the colours
within preferences box
Check out this thread:
I have eclipse with pydev and i set the background to black and text white. now when i click on any word, is highlighted in a yellow color

A: This selection is on:
Preferences -> General -> Editors -> Text Editors
Then on the Appearance color options you can change the "Selection background color"