text:
Q: Web API beside ASMX in the same project? I have some web services in a asp.net web application using asmx.
as it goes I need to provide more web services here and I'm going to use Web API instead of traditional asmx.
the question is, Can I have these to types of web service in the same project which is going to deploy on the same web host?
here is the solution explorer:

as you can see, the CNIS.asmx and Webservise_TCIKH.asmx are serving from long time ago, and now I need to add more web services using Web API, but the old web services should remain functional .
I've added a new API controller called AirKindController.cs in the folder called CNISAPI. this is the implementation:
public class AirKindController : ApiController
{
    CNISDataContext db;
    private AirKindController()
    {
        db = new CNISDataContext();
    }
    // GET api/<controller>
    public IEnumerable<AirKind> Get()
    {
        return db.AirKinds;
    }

BUT, when I request the http://localhost:3031/CNISAPI/api/AirKind  or http://localhost:3031/api/AirKind there is an error of 404! Am I calling right? or it is not possible to have these two types of web services in the same place?
Thanks in advance!
EDIT: (solution)
by  @moarboilerplate guidance, I've added a Global.asax to my project and add the route configuration in the Application_Start method like below:
protected void Application_Start(object sender, EventArgs e)
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

the WebApiConfig.Register is here:
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Now I'm able to get the xml formatted output by requesting http://localhost:3031/api/AirKind.
Problem SOLVED!!!

A: As this problem is solved in the question itself, I decide to add the answer in the Answers section:
by  @moarboilerplate guidance, I've added a Global.asax to my project and add the route configuration in the Application_Start method like below:
protected void Application_Start(object sender, EventArgs e)
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

the WebApiConfig.Register is here:
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Now I'm able to get the xml formatted output by requesting http://localhost:3031/api/AirKind.
Special thanks to @moarboilerplate .


text:
Q: opencv_traincascade.Unspecified error (No element name has been given) I'm trying to train my own cascade, but get the following error:
Unspecified error (No element name has been given) in cv::operator
 <<, file C:\builds\2_4_PackSlave-win64-vc11-shared\opencv\modules\core\include\
opencv2/core/operations.hpp, line 2910

I made these steps:

*

*I cut 20 photos of the object so that they remained only the desired object

*Resize to 30x18

*Make objectSamples.dat file like this :

object(1).jpg 1 0 0 30 18
object(10).jpg 1 0 0 30 18
object(11).jpg 1 0 0 30 18

And negatives.dat like  :
negatives\1.jpeg
negatives\10.jpg
negatives\11.jpg
size of pic ~ 500x500

4.Make vec file:
opencv_createsamples -info objectSamples.dat -vec objectSamples.vec -w 30 -h 18 -num 20
5.Show samples ( my pictures are shown entirely) : opencv_createsamples  -vec objectSamples.vec -w 30 -h 18
6.Try to train : opencv_traincascade -data Cascade -vec objectSamples.vec -bg negatives.dat -numPos 10 -numNeg 10 -numStages 2 -featureType HAAR -w 30 -h 18
But get an error:

What am I doing wrong?
I read these articles and the answer, but I didn't understand, in what a problem:

*

*trouble-when-use-opencv_traincascadeexe

*haartraining tutorial

*docs.opencv traincascade

Increased the number of images to 1000 positive and 2000 negatives
opencv_traincascade -data Cascade -vec boobsSamples.vec -bg negativesBig/negatives.txt -numPos 400 -numNeg 1000 -numStages 2 -featureType HAAR -w 30 -h 18 -mode ALL

Geting the same error.

A: Problem solved!
I copied the opencv_traincascade.exe to a folder of images. When I ordered the full path to the opencv_traincascade.exe in the library, the problem disappeared.
F:\OpenCV\opencv\build\x64\vc11\bin\opencv_traincascade -data Cascade -vec positives.vec -bg negativesBig/negatives.txt -numPos 400 -numNeg 1000 -numStages 2 -featureType HAAR -w 30 -h 18 -mode ALL

redpajama_set_name: RedPajamaStackExchange


text:
Q: android layout radiogroup position I have radiogroup :
<RadioGroup android:layout_height="wrap_content"
             android:layout_gravity="center_horizontal|bottom"
             android:orientation="horizontal"
             android:layout_width="match_parent"
             android:background="@drawable/overlay_2"
             android:id="@+id/rgSettings">`

             <RadioButton android:layout_width="140dp"
                          android:layout_height="100dp"
                          android:id="@+id/s_mph"
                          android:background="@drawable/settings_speed_mph"
                          android:button="@android:color/transparent"
                          android:layout_gravity="center_vertical|left"/>

             <RadioButton android:layout_width="140dp"
                          android:layout_height="100dp"
                          android:id="@+id/s_kph"
                          android:checked="false"
                          android:background="@drawable/settings_speed_kph"
                          android:button="@android:color/transparent"
                          android:layout_gravity="center"
                          android:gravity="right"/>

</RadioGroup>

Link in screenshot : http://joxi.ru/A5GhUxjKTJBQH7uRaK4
(1) radiogroup
(2) - (3) its radio buttons.
I need radibutton (2) set in position - left, radiobutton (3) set in right position. What do I need for this?
Add:
i need set first button set left position in radiogroup, secondary button set in right position radiogroup. Like This: joxi.ru/FqKhUxjKTJBsH5OWteQ

A: Why You are setting the button that You need on the left side as first? Just switch it:
         <RadioGroup android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:layout_width="match_parent"
         android:background="@drawable/overlay_2"
         android:id="@+id/rgSettings">

         <RadioButton android:layout_width="140dp"
                      android:layout_height="100dp"
                      android:id="@+id/s_kph"
                      android:checked="false"
                      android:background="@drawable/settings_speed_kph"
                      android:button="@android:color/transparent"
                      android:layout_gravity="center_vertical|left"
                      android:gravity="right"/>

         <RadioButton android:layout_width="140dp"
                      android:layout_height="100dp"
                      android:id="@+id/s_mph"
                      android:background="@drawable/settings_speed_mph"
                      android:button="@android:color/transparent"
                      android:layout_gravity="center_vertical|right"/>

         </RadioGroup>

Also, You can play a little bit with the layout_margin attributes to make space between the buttons.


text:
Q: Exception in thread "main" java.lang.NoSuchMethodError: org.apache.commons.beanutils.PropertyUtilsBean I'm trying to read properties file and got stuck with error which is given below.I have written an Scala package where i'm trying to read properties file and call into abc.scala program.Any help will be appreciated.
File:- xyz.properties
driver = "oracle.jdbc.driver.OracleDriver"
url = "jdbc:oracle:thin:@xxxx:1521/xxxx.xxxx"
username = "xxx"
password = "xxx"
input_file = "C:\\Users\\xxx\\test\\src\\main\\resources\\xxxx.xlsx"

build.sbt
name := "xxx.xxxx.xxxxx"

scalaVersion := "2.10.6"

ivyScala := ivyScala.value map{ _.copy(overrideScalaVersion = true) }

libraryDependencies ++= Seq(
"org.apache.spark" %% "spark-core" % "2.1.0",
"com.databricks" %% "spark-csv" % "1.5.0",
"org.apache.commons" % "commons-configuration2" % "2.1.1",
"commons-beanutils" % "commons-beanutils" % "1.9.3",
"org.apache.spark" %% "spark-sql" % "2.1.0",
"org.scala-lang" % "scala-xml" % "2.11.0-M4"  )

Package
package com.xxx.zzzz.xxx1

        import java.io.File
        import org.apache.commons.configuration2.builder.fluent.{Configurations, Parameters}

        object Configuration {

          var config = new Configurations()
          var configs = config.properties(new File("xyz.properties"))

          var inputFile = configs.getString("input")
          var userName = configs.getString("user_name")
          var password = configs.getString("passwd")
          var driver = configs.getString("driver")
          var url = configs.getString("Url")

        }

Main Program abc.scala
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.SQLContext
import package com.xxx.zzzz.xxx1.Configurations
import org.apache.commons.beanutils.PropertyUtils

object ItalyPanelData {
  def main(args: Array[String]): Unit = {

        //Logger.getRootLogger().setLevel(Level.OFF)

        println("Inside main program"+ Configuration.driver)
        //Set the properties for spark to connect the oracle database
        val dbProp = new java.util.Properties
        dbProp.setProperty("driver", Configuration.driver)
        dbProp.setProperty("user", Configuration.userName)
        dbProp.setProperty("password", Configuration.password)

        //Create a connection to connect spark
        val conf = new SparkConf().setAppName("Simple Application").setMaster("local")
        val sc = new SparkContext(conf)
        val sqlContext = new SQLContext(sc)

    //exception handlying
    try {
      //Create dataframe boject
      val df = sqlContext.read
        .option("location", Configuration.inputFile)        //Initiating input path
        .option("sheetName", "xyz")                       //Give the SheetName
        .option("useHeader", "true")                        //It takes the header name from excel sheet
        .option("treatEmptyValuesAsNulls", "true")
        .option("inferSchema", "true")
        .option("addColorColumns", "false")
        .load()
      // Write into oracale database
      df.write.mode("append").jdbc(Configuration.url, "xyz", dbProp)
    }
    catch {

        case e: Throwable => e.printStackTrace();
    }

      }
}

Error
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.commons.beanutils.PropertyUtilsBean.addBeanIntrospector(Lorg/apache/commons/beanutils/BeanIntrospector;)V
at org.apache.commons.configuration2.beanutils.BeanHelper.initBeanUtilsBean(BeanHelper.java:631)
at org.apache.commons.configuration2.beanutils.BeanHelper.<clinit>(BeanHelper.java:89)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.sun.proxy.$Proxy0.<clinit>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:739)
at org.apache.commons.configuration2.builder.fluent.Parameters.createParametersProxy(Parameters.java:294)
at org.apache.commons.configuration2.builder.fluent.Parameters.fileBased(Parameters.java:185)
at org.apache.commons.configuration2.builder.fluent.Configurations.fileParams(Configurations.java:602)
at org.apache.commons.configuration2.builder.fluent.Configurations.fileParams(Configurations.java:614)
at org.apache.commons.configuration2.builder.fluent.Configurations.fileBasedBuilder(Configurations.java:132)
at org.apache.commons.configuration2.builder.fluent.Configurations.propertiesBuilder(Configurations.java:238)
at org.apache.commons.configuration2.builder.fluent.Configurations.properties(Configurations.java:282)
at com.rxcorp.italy.config.Configuration$.<init>(Configuration.scala:8)
at com.rxcorp.italy.config.Configuration$.<clinit>(Configuration.scala)
at com.rxcorp.paneldataloading.ItalyPanelData$.main(abc.scala:12)

A: Such exceptions are an indication of a version incompatibility.
Meaning: the code that you have written (or more likely: the one of the libraries under the surface) wants to call a method
org.apache.commons.beanutils.PropertyUtilsBean.addBeanIntrospector(BeanIntrospector[]);

but the thing is: at runtime, the class file for PropertyUtilsBean does not contain that method.
Thus: you have to step back and understand the components in your stack, and check out their version requirements on the Apache commons library.
And you get more ideas when looking into the javadoc for that method; as it says: Since: 1.9 there.
In other words: this method was added Apache commons 1.9; so some piece of your stack expects at least that version of commons; but your classpath in the JVM that executes the whole thing ... has an older version.
So: check the classpath for apache commons; and most likely you are good by simply updating to a newer version of apache commons. (and yes, maybe that will mean more "hard" debug work; as at least your build settings include a newer version of apache commons).

A: I guess I have a similar problem. Apache commons configuration 2.7 is used in our project together with apache commons BeanUtils 1.9.
Unfortunately another library we use is jxls-reader 2.0.+ and this one references commons-digester3 library.
So the beanutils 1.9 as well as the commons-digester3 lib both have a class packaged org.apache.commons.beanutils.PropertyUtilsBean. But commons-digester3's version does not have the above mentioned method bringing us to the same dilemma as you have.
For now we can be lucky as our windows servers loading the "correct" version of beanutils first whereas some developers using a mac have it the other way round where the digester3 package is loaded first bringing up the no-such-method-error you have.
Not sure what can be our workaround here.
Anyway check if you have the class two times on your classpath and find out who's using it by checking all your pom.xmls of dependent libs on the classpath. Finally you might be lucky to remove some library if its not needed by your code (chances are low :-( though)

Update 10thNov: I exluded the commons-digester3 from the jxls-reader dependency:
<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls-reader</artifactId>
    <version>2.0.3</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-digester3</artifactId>
        </exclusion>
    </exclusions>
</dependency>

So that the commons-digester with classifier "with-deps" from jxls-reader won't get resolved and I pull it in explicitely in our pom.xml but only the normal jar without packaged classes of commons-logging, commons-beanutils...


text:
Q: Clustering points using QGIS expressions or virtual layers Is there any way of clustering points using QGIS expressions or virtual layers?
I need a dynamic solution so I cannot use tools that create static layers and as a requirement I cannot use python.
Point cluster symbology is not an option either because I need to have control over labels for clusters.
I've tried the 'easy' way creating buffers in a virtual layer (creating buffers around points, dissolving overlapping buffers and symbolizing buffer centroids with the number of points inside each dissolved buffer) but the result is not as good as I expected despite trying with different buffer distances. Bigger distances group too many points together and smaller distances still group too many points in some areas but do not group many other points that look too close at my working scale and I expected to be grouped.
With Point cluster symbology I get this:

And with my buffer approach I get this (with the buffer distance I found to give 'best' results):

For more details this is the code for the virtual layers (the point layer is called 'Point_elem'):

*

*Dissolved buffers ('Point_elem_Buffer' layer)

WITH RECURSIVE parts AS (
  SELECT t.total, 1 AS ref_id
  FROM totals AS t
  UNION ALL
  SELECT t.total, ref_id + 1 AS ref_id
  FROM totals AS t
  INNER JOIN parts AS p ON p.ref_id < t.total
  ),

totals AS (
  SELECT NumGeometries(geom) AS total
  FROM merged_buff
  ),

merged_buff AS (
  SELECT ST_Union(ST_Buffer(geometry, 11.5)) AS geom
  FROM "Point_elem"
  )

SELECT p.ref_id, GeometryN( m.geom, p.ref_id) as geom
FROM parts AS p
INNER JOIN merged_buff AS m;

*

*Centroids with point count and other stuff for labeling  ('Point_elem_Buffer_Centroids' layer)

SELECT ST_CENTROID(buff.geometry),
buff.ref_id,
GROUP_CONCAT(ext.elem_code) as codes,
count(*) as elem_count
FROM "Point_elem_Buffer" as buff,
"Point_elem" as ext
WHERE ST_Within(ext.geometry, buff.geometry)
GROUP BY buff.ref_id;


text:
Q: How to view "Events per second" in Logstash? I am building an alert using Elasticsearch and I need to access the data for one of the logstash nodes for how many events it is receiving per second. On the Monitoring (formally Marvel) tab, this information is readily available in graph format. Is there anyway to get that same information using an ELK API aside from scripting something?

A: Take a look at the Logstash Metrics filter plugin


text:
Q: What is in the assembly registers before they are used in program? what is in the assembly registers before they are initialized ? If i am working with logic operands like AND, OR, XOR and only use it for example like this: and al,00000000b or and al,11111110 what will be the value in AL register ?

A: Unless your code is the very first instruction the machine runs after power-on (i.e. the firmware in ROM or flash), it will have been called from some other code that left something in registers.
In some cases (like the OS starting a fresh process), it may choose to zero all the registers before switching to user-space to avoid leaking any kernel information that might have been left in registers.  (e.g. Linux does this on execve).
Registers are like global variables, but truly global across processes.  They always have some value.  In most cases you can't assume anything.  and al, 1 might produce 0 or 1, you don't know; it depends on what "random" garbage was left in the low bit of EAX / RAX before your code ran.  It's usually not truly random, but it might as well be because there's no rule that governs what's allowed to be there.  e.g. it might be an address that some other code was using for something, or some data it was copying around.
It might be useful to consider what state your program will leave the registers in.  e.g. when your program exits to the OS.  Or for a function that returns, what values are in the call-clobbered (volatile) registers:  Other than the return-value in EAX (if you return a 32-bit integer or pointer), you can leave anything you want in ECX and EDX.
For the code you're returning to, the register state of regs that aren't call-preserved is basically the same situation as at the top of your function: it can't assume anything because some other code could have left anything.


text:
Q: Using python's mock to temporarily delete an object from a dict I am writing a test for some code that checks for a value in os.environ (I know this isn't optimal, but I have to go with it).  I would like to remove an entry from os.environ for the duration of the test.  I am not sure if mock supports this.  I know patch.dict can be used to modify an item, but I want the key/value pair removed.  I would like something along these lines:
print os.environ
{ ... , 'MY_THING': 'foo', ... }

with mock.patch.dict.delete('os.environ', 'MY_THING'):
    # run the test
    # ( 'MY_THING' in os.environ ) should return False

# everything back to normal now
print os.environ
{ ... , 'MY_THING': 'foo', ... }

Is there a way to perform such a feat?

A: mock.patch.dict doesn't quite work like your sample desired code. patch.dict is a function which requires an argument. You probably want to use it like this:
>>> import os
>>> import mock
>>> with mock.patch.dict('os.environ'):
...     del os.environ['PATH']
...     print 'PATH' in os.environ
...
False
>>> print 'PATH' in os.environ
True

A: For deleting the item, you can simply use:
my_thing = os.environ['MY_THING']  # Gotta store it to restore it later
del os.environ['MY_THING']

And then restore it with:
os.environ['MY_THING'] = my_thing

A: For those using Pytest, note that the answers involving context-managers do not work. Instead, Pytest provides a built-in fixture for Mocker, which automatically assumes a context-manager roll:
import os

def test_before_change():
    print('before change: ' + os.environ['PATH'])

def test_env_change(mocker):
    mock.patch.dict(os.environ)
    del os.environ['PATH']
    print('PATH would go here...if I had one! ' + os.environ['PATH'])

def test_before_change():
    print('after change: ' + os.environ['PATH'])

# now run the pytest


text:
Q: Is there a R function which would return a predefined min & max value if the computed value exceeds the range? I have a formula. When r calculates the value, if the result is between 0 and 1, the function should return the computed value. But, if it is below 0, the function should return 0, and if it is above 1, the function should return 1.
Is there an efficient way to do it without using the if function?
I found a javascript code that does what I want to do in R. Here it is:
clip = (a, b, t) => Math.min(Math.max(t, a), b)

A: In Javascript, you could guard with Math.min and Math.max with lower and upper bound.

const
    x = (y, z) => Math.max(Math.min(y - z, 1), 0);

console.log(x(1, 2));   // 0
console.log(x(2, 0));   // 1
console.log(x(1, 0.5)); // 0.5


text:
Q: Construct2 - Layout transition is not showing animations I am having a problem with my game: when I press the "go back to main menu" button at the pause menu, I go back to the main menu layout. The problem is: It does not run sprites' animations of the main menu, just movements. How can I fix it? Oh, and by the way, reset layout did not work. I tried debugging it and found out that the sprite animation is playing, but the current frame is not changing. PLease help me

A: Without taking a look at your spritesheet, I'd do the following to try to find the bug:
1-See if animation speed is set to 0 or if it's being set to 0 somewhere in your events.
2-See the time scale. I, personally, use time scale = 0 to make pauses. I think you can bug your animations if you do not set it properly again to 1.0 but so far I don't think this has happened to me yet so I'm not sure.
3-See if your animation is set to loop. Perhaps C2 is considering that your animation has already ended its first run.

A: I just had a similar problem. Turned out I was pausing and setting the time scale to 0 and then returning to the title screen, only after reading this did I realize I needed to change the timescale bqck to 1.


text:
Q: Viewing SQL queries from all sources I found this picture in a document. It shows the queries running on a given SQL database. It looks similar to DBeaver software. However, I couldn't find a way to get to this screen from DBeaver. Can someone please help me to figure out what software this is? It would be really helpful to troubleshoot performance-related issues.

A: That's MySQL's SHOW PROCESSLIST.
IN ( SELECT ... ) often optimizes poorly; try to rewrite using a JOIN.
This may help:
INDEX(status, Calendar_Date, Date_Received)

For more help we need to see the queries and SHOW CREATE TABLE.  You can obfuscate the names, but don't make it too hard to read.
{The TIMESTAMP qualifier is not required.)
Frameworks (eg, DBeaver) are handy for getting started.  But ultimately you need to understand the underlying database.


text:
Q: problem with ifelse and is.table or is.matrix in R When I use ifelse function with is.table or is.matrix I get unwanted results. Whereas if I use an if statement I get the result I want. Example below.
x <- table(state.division, state.region)

colSums(x) ## What I am supposed to get in the code below
rowSums(x) ## Same

ifelse(is.table(x), colSums(x), 0) ## Get only the first element of colSums(x)
ifelse(is.matrix(x), apply(x, 2, sum), 0) ## Tried with apply instead but same results
ifelse(is.matrix(x), rowSums(x), 0) ## Same for rowSums
ifelse(is.table(x), apply(x, 1, sum), 0)

if (is.table(x)) colSums(x) ## All fine

Anybody know what's going on?


text:
Q: Настройка маршрутизатора Cisco 891-F Доброго времени суток.
Имеется маршрутизатор Cisco 891-f. Необходимо с его помощью организовать локальную сеть таким образом:

*

*Интерфейсы Gigabit Ethernet 0, 4, 5 Смотрят в одну подсеть с адресом 192.168.50.1/24

*Интерфейс Gigabit Ethernet 1 - в подсеть с адресом 192.168.55.1/24

*Интерфейс Gigabit Ethernet 2 - в подсеть с адресом 192.168.60.1/24

*Интерфейс Gigabit Ethernet 8 - к провайдеру

Так как интерфейсы GigabitEthernet 0-7 представлены как интерфейсы второго уровня, для поддержки IP протокола были созданы Vlan интерфейсы, на которые приземляются соответствующие интерфейсы роутера. Протестировать работоспособность сети в данный момент не представляется возможным, поэтому я хотел узнать, что необходимо добавить в конфигурационный файл, чтобы данная сеть могла работать.
Current configuration : 3378 bytes
!
! Last configuration change at 14:26:39 UTC Fri Apr 22 2016 by admin
!
version 15.4
service timestamps debug datetime msec
service timestamps log datetime msec
service password-encryption
!
hostname kaf
!
boot-start-marker
boot-end-marker
!
!
no logging console
enable secret 5 $1$gCIa$BcurCO2Mk2PJUkYC6apSl.
enable password 7 08701E1D5D4C
!
aaa new-model
!
!
!
!
!
!
!
aaa session-id common
no process cpu extended history
no process cpu autoprofile hog
!
!
!
ip dhcp excluded-address 192.168.60.1

ip dhcp pool RE1_TEST_POOL
host 192.168.69.69 255.255.255.0
client-identifier 0100.0e2e.6af9.39
client-name RE1_TEST
!
!
!
ip domain name dozen.mephi.ru
ip cef
no ipv6 cef
!
no cdp run
!
ip ssh time-out 30
ip ssh authentication-retries 2
ip ssh source-interface GigabitEthernet8
ip ssh version 2
!
interface BRI0
 no ip address
 encapsulation hdlc
 shutdown
 isdn termination multidrop
 no cdp enable
!
interface FastEthernet0
 description Private router subnet interface
 ip address 192.168.69.1 255.255.255.0
 duplex auto
 speed auto
 no cdp enable
!
interface GigabitEthernet0
 switchport access vlan 10
 no ip address
 no cdp enable
!
interface GigabitEthernet1
 switchport access vlan 20
 no ip address
 no cdp enable
!
interface GigabitEthernet2
 switchport access vlan 30
 no ip address
 no cdp enable
!
interface GigabitEthernet3
 switchport access vlan 40
 no ip address
 shutdown
 no cdp enable
!
interface GigabitEthernet4
 switchport access vlan 20
 no ip address
 no cdp enable
!
interface GigabitEthernet5
switchport access vlan 20
no ip address
no cdp enable
!
interface GigabitEthernet8
 ip address 192.168.50.1 255.255.255.0
 duplex auto
 speed auto
 no cdp enable
!
interface Vlan1
 no ip address
!
interface Vlan10
 description Kaf subnet interface
 ip address 192.168.51.1 255.255.255.0
 ip accounting output-packets
 ip nat inside
 ip virtual-reassembly in
!
interface Vlan20
 description Unix server subnet interface
 ip address 192.168.55.1 255.255.255.0
 ip accounting output-packets
 ip nat inside
 ip virtual-reassembly in
!
interface Vlan30
 description Web server subnet interface
 ip address 192.168.60.1 255.255.255.0
 ip nat inside
 ip virtual-reassembly in
!
interface Async3
 no ip address
 encapsulation slip
!
ip forward-protocol nd
no ip http server
no ip http secure-server
!
!
!
ip access-list standard ACL_REMOTE_ACCESS
 permit 192.168.69.2
!
no service-routing capabilities-manager
!
snmp-server community public RO
!
!
!
control-plane
!
!
mgcp behavior rsip-range tgcp-only
mgcp behavior comedia-role none
mgcp behavior comedia-check-media-src disable
mgcp behavior comedia-sdp-force disable
!
mgcp profile default
!
!
!
!
!
!
!
line con 0
 exec-timeout 0 0
 no modem enable
 line aux 0
line 3
 modem InOut
 speed 115200
 flowcontrol hardware
line vty 0 4
 exec-timeout 0 0
 privilege level 15
 password 7 12485744465E
 logging synchronous
 transport input ssh
 transport output ssh
!
scheduler allocate 20000 1000
!
!
!
end

A: По всей видимости, не настроен NAT. Необходимо добавить:
ip access-list extended 140
permit ip 192.168.50.0 255.255.255.0 any
permit ip 192.168.55.0 255.255.255.0 any
permit ip 192.168.60.0 255.255.255.0 any
ip nat inside source list 140 interface (WAN-интерфейс) overload

Далее надо посмотреть, какой у тебя тип WAN и правильно его настроить (сейчас на Gi8 серый IP висит). После чего повесить на него NAT:
    interface (WAN-интерфейс) ip nat outside
и шлюз:
ip route 0.0.0.0 0.0.0.0 (WAN-интерфейс) (опционально: IP провайдерского устройства)

A: на беглыф взгляд вроде норм.
interface GigabitEthernet8
nat outside добавить надо есали это провайдер
+ нет маршрута на шлюз провайдера.


text:
Q: Issue Using ViewPager Indicator with Jake Wharton Library I have downloaded the library and properly included into my android studio project
I am not able to see Circle indicator even after using library:
Here is my code:
MAIN FILE:
 public class MyActivity extends FragmentActivity implements  OnPageChangeListener {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my);
            List<Fragment> list = new ArrayList<Fragment>();
            list.add(new MyFragment());
            list.add(new MyFragment());
            list.add(new MyFragment());
            MyPagerAdapter a = new MyPagerAdapter(getSupportFragmentManager(), list);
           ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
            pager.setAdapter(a);
            CirclePageIndicator mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
            mIndicator.setViewPager(pager);

        }

MyPagerAdapter.java
public class MyPagerAdapter extends FragmentPagerAdapter {
    List<Fragment> fragments;
    public MyPagerAdapter(FragmentManager fm,List<Fragment> f) {
        super(fm);
        this.fragments = f;
    }

    @Override
    public Fragment getItem(int arg0) {

        return fragments.get(arg0);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return fragments.size();
    }
}

MyFragment:
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanse) {
        final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }

activity_my.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <com.viewpagerindicator.CirclePageIndicator
            android:id="@+id/indicator"
            android:padding="10dip"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            />
</android.support.v4.view.ViewPager>

</RelativeLayout>

fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/gallery"
        android:src="@drawable/pic1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Output:


text:
Q: Error en java con escribir en fichero Estoy intentando crear un programa en java que cuando introduzca una palabra de 5 letras  me compare si las letras son iguales a una palabra aleatoria y luego escriba el resultado en un fichero, pero me da este error y no entiendo por qué no va, si además estoy capturando los errores con un try y un catch.
Mi código:
Cogemos los paquetes

package curso;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

#Aquí creamos mi clase main donde está el array de las palabras aleatorias y funciona cogiendo una plabra y probando con cada letra si coincide

public class main {
    El array de la palabra aleatoria
    public static List<String> getPalabras(){
        return Arrays.asList("coche",
                            "ambar",
                            "raton",
                            "pizza",
                            "perro",
                            "pasta",
                            "quien",
                            "cromo",
                            "salto",
                            "donde",
                            "falta",
                            "barco",
                            "balsa",
                            "guiar",
                            "horno",
                            "lugar",
                            "mirar",
                            "naipe",
                            "pinta",
                            "rural",
                            "sonar",
                            "tocar",
                            "tener",
                            "letra",
                            "igual",
                            "tonto",
                            "total",
                            "bombo",
                            "morir",
                            "motin",
                            "matiz",
                            "mundo",
                            "grupo",
                            "saber",
                            "cinco",
                            "hacer",
                            "perla",
                            "dejar",
                            "epoca",
                            "sobre",
                            "gesto",
                            "rival",
                            "lunes",
                            "nadie",
                            "paron",
                            "ideal",
                            "gasto",
                            "renta",
                            "hasta",
                            "hacia");

    }

    public static void main (String[] args ){

    Escritura del fichero  usando filewriter

    FileWriter archivo;
    try {
        archivo = new FileWriter("C:\\Users\\alber\\OneDrive\\Documentos\\fichero.txt");

    BufferedWriter bw = new BufferedWriter(archivo);

    int elegida = (int) (Math.random() * 50);
    Scanner scanner = new Scanner (System.in);

    System.out.println("Ingrese una palabra");
     String palabra = scanner.next();
    Aquí es donde compruebo que tengo 5 letras
        if (palabra.length()== 5) {

                Aquí hago la comparación letra por letra
                for(int i=0; i < palabra.length();i++) {
                    if(palabra.charAt(i)==getPalabras().get(elegida).charAt(i)) {
                        System.out.println(palabra.charAt(i) + "Es igual "  + getPalabras().get(elegida).charAt(i));
                        bw.write(palabra.charAt(i) + "Es igual "  + getPalabras().get(elegida).charAt(i));
                        bw.close();
                    }else {

                        System.out.println(palabra.charAt(i)+ " " + "No es igual " + " " + getPalabras().get(elegida).charAt(i));
                        bw.write(palabra.charAt(i) + "Es igual "  + getPalabras().get(elegida).charAt(i));
                        bw.close();
                    }
                }

            }

        else{
            int intentos=0;
            boolean resultado = false;
            while(resultado == false || intentos <= 5) {
                intentos ++;
                System.out.println("Ingrese una palabra");
                palabra = scanner.nextLine();
                if(palabra.length()==5) {
                     resultado = true;

                }

            }
                if(intentos==5) {

                    System.out.println("Has fallado el juego vuelva a intentarlo");
                }

        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
}

Este es el fallo
Ingrese una palabra
adios
a No es igual  h
java.io.IOException: Stream closed
d No es igual  o
    at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107)
    at java.base/java.io.BufferedWriter.write(BufferedWriter.java:224)
    at java.base/java.io.Writer.write(Writer.java:249)
    at arrays/curso.main.main(main.java:93)

A: Sencillo. Tienes unos for y en cada iteración escribes y luego cierras. La segunda iteración del ciclo for, el bufferedwriter ya está cerrado y no puedes escribir.
Esa instrucción bw.close() va al finaaaaaaaaaaaaaal de todo, ojalá en un finally de ese try-catch (revisa cómo funciona) y con eso aseguras que cierras todo al final de la ejecución del programa.


text:
Q: Dynamically Scaffolded Views Apparently Not Generated IMPORTANT ---> ... it looks like this is a currently known bug in Grails 3.1.1 (Issue #9729) Apparently its been fixed in 3.1.2 ...
--- My Original Post is Below ---
It appears as though no views are generated when executing a dynamically scaffolded controller. I'm using Grails 3.1.1 (w/ scaffolding plugin specified in dependencies), JDK 8, all running on OSX...
My test case is a very simple 'Book' example with the following domain class and controller...
// Domain Class...
package scaffoldtest

class Book {

    String name
    String author

    static constraints = {
    }
}

// Controller (scaffolded)...
package scaffoldtest

class BookController {

    static scaffold = Book

}

When I issue a run-app command and navigate to http://localhost:8080/book/index I get the following exception...
Error 500: Internal Server Error
URI: /book/index
Class: javax.servlet.ServletException
Message: Could not resolve view with name 'index' in servlet with name 'grailsDispatcherServlet'

...and FWIW, I also cannot see any sign of the generated view files down the "/build" tree... Also, and again FWIW, I believe I've read somewhere that dynamic scaffolding was temporarily removed during the initial versions of Grails 3, but my understanding (and the Grails manual concurs) is that dynamically generated views were put back in. In any case, I'm not seeing why the above dynamic scaffolding example doesn't work...

A: FYI, that bug should be fixed in Grails 3.1.2, which was released earlier today. See the changelog at https://github.com/grails/grails-core/issues?q=milestone%3Agrails-3.1.2.


text:
Q: PHP for each e-mail in array, send unique key from another array I'm more of a front-end dev and I'm not very far with PHP. I mostly use jquery and reactjs for my applications. I'm creative when it comes to design, but I got barely any inspiration while writing something functional. I need a way to send for each unique e-mail from an array, a random key from another array to that email, but so that each email get's an unique key.

A: That doesn't sound difficult. Try something like this.
$emails = ["first@example.com", "second@example.com"];

$uniqueEmails = array_unique($emails);
$uniqueKeys = ["uniq1", "uniq2"];

foreach ($uniqueEmails as $key => $email) {

    //TODO: sendMail($email, $key);

}

The array_unique() function is used to remove duplicates from your array.
As far as I understand your question, you want to send the unique key to that email address. The PHP mail function can do that for you: http://php.net/manual/en/function.mail.php.

A: *

*Be sure that every array element is unique (http://php.net/manual/en/function.array-unique.php)

*Do foreach with this array && on every iterate do the following (Take random key from second array by index && unset it (to avoid duplicate)) && send email


text:
Q: IntelliJ Kotlin - MainKt run/debug configuration unavailable, cannot run project I'm trying to run a basic Kotlin main file but the problem is I don't have any run/debug configurations available.
My main.kt file is under src>main and is a very simple Helloworld program. See below image.
When I enter Add Configuration>Kotlin and type MainKt in Main Class, I get Warning: Class MainKt not found. In previous projects MainKt has been the default and I haven't had to add a configuration manually. Has anyone else come across this issue?
Image of project
Run/Debug Configuration image
Project Structure image
If I hit Run(in toolbar)>Run you can see no available configurations
EDIT: added Main module to source and MainKt class is now available in Add Run/Debug Configuration, but I get the error in below image, "Error: Could not find or load main class MainKt
Caused by: java.lang.ClassNotFoundException: MainKt"
Error: Cannot find MainKt

A: The source for the class MainKt (main.kt) does not appear to be under your sources root (src/main/kotlin), it's one level up if I interpret the UI of intellij correctly. Try moving it into the kotlin/ directory.


text:
Q: IEEE Access latex file forces the volume and year to be listed as volume 4 2016, how do I change that? When compiling the latex template for IEEE access file, it forces the content in the bottom of each page to be "Volume 4, 2016". How do I change that?
See code below:
\documentclass{ieeeaccess}
\usepackage{cite}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{algorithmic}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{textcomp}
\usepackage{subfig}

\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
        T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}

\begin{document}
\history{Date of publication xxxx 00, 0000, date of current version xxxx 00, 2019.}
\doi{10.1109/ACCESS.2019.DOI}

\title{BLA}
\author{\uppercase{R D}\authorrefmark{1}, \IEEEmembership{Senior Member, IEEE}}
\address[1]{BLA)}
\tfootnote{This work was supported in part by CMC Microsystems for the provision of software tools.}

\markboth
{R.D \headeretal: BLA}
{R.D \headeretal: BLA}

\corresp{Corresponding author: RD (e-mail: BLA).}

\begin{abstract}
BLA
\end{abstract}
%...etc
 \end{document}

A: The year value is hardcoded in the class, which is a bit odd. However, you can patch the footer commands with the etoolbox package to insert a custom macro. The volume is controlled by defining \thevol, which works without patching.
MWE:
\documentclass{ieeeaccess}
\usepackage{cite}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{algorithmic}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{textcomp}
\usepackage{subfig}
\usepackage{etoolbox}
%%% Define variable values
\def\thevol{3}
\def\myyear{2019}
%%% Patch the footer commands
\makeatletter
\patchcmd{\@evenfoot}{2016}{\myyear}{}{}
\patchcmd{\@oddfoot}{2016}{\myyear}{}{}
\makeatother
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
        T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}

\begin{document}
\history{Date of publication xxxx 00, 0000, date of current version xxxx 00, 2019.}
\doi{10.1109/ACCESS.2019.DOI}

\title{BLA}
\author{\uppercase{R D}\authorrefmark{1}, \IEEEmembership{Senior Member, IEEE}}
\address[1]{BLA)}
\tfootnote{This work was supported in part by CMC Microsystems for the provision of software tools.}

\markboth
{R.D \headeretal: BLA}
{R.D \headeretal: BLA}

\corresp{Corresponding author: RD (e-mail: BLA).}

\begin{abstract}
BLA
\end{abstract}
abc
\EOD
\end{document}

Result:

A: You can redefine the volume and year easily like below in your tex file :
\renewcommand{\thevol}{15}
\renewcommand{\theyear}{2020}

However, the year might not change as the IEEE access style class ieeeaccess.cls has mistakenly used hard coded year instead of using this \theyear variable.
In that case, you can find the 2016 word in your ieeeaccess.cls file and replace with \theyear. Do not change the \def\theyear{2016} line in the ieeeaccess.cls file though :)

A: Add the below code before the \begin{document} tag. It has compiled for me perfectly. The output obtained from the below code is given in the screenshot below:

Here we have not changed the volume of the journal. this should be changed by the editing team of the journal. However, the latest year can be changed as there will be no current volumes for the previous years.
% FIX FOR ADDING CORRECT VOLUME AND YEAR AS IEEE ACCESS DEFAULT FORMAT IS SHOWING VOLUME 6, 2016. THE VOLUME XX NEEDS TO BE CHANGED TO THE CURRENT VOLUME IN THE BELOW LINE
% FIX for VOLUME AND YEAR STARTS HERE
\def\THEYEAR{2022}
\gdef\thevol{XX}
\makeatletter
\ifjtehm
  \def\headerlogo{\raisebox{-2pt}{\includegraphics[width=7.61pc]{jtehmLogo.png}}}
  \def\ps@titlepage{%
     \def\@oddhead{\parbox[t]{\textwidth}{\mbox{}\\[-6.3mm]{\raisebox{5pt}%
       {{\titlepageheaderfont\color{accessblue}\headName}}}%
       \hfill\headerlogo\mbox{}\vspace*{-3.5mm}\par\rule{30.54pc}{.3pt}}}
     \def\@evenhead{\parbox[t]{\textwidth}{\mbox{}\\[-6.3mm]\mbox{}\headerlogo%
       \hfill{\raisebox{5pt}{{\titlepageheaderfont\color{accessblue}\headName}}}%
       \vspace*{-3.5mm}\par\mbox{}\hfill\rule{30.54pc}{.3pt}}}
     \def\@oddfoot{\raisebox{3pt}{%%
       \hbox to 0pc{\hbox to \textwidth{{\footervolfont VOLUME\ \thevol, \THEYEAR}\hfill\mbox{}}}%
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footervolfont\@pubid}\hfill\mbox{}}}%
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footerpagefont\@artnum}}}%\hspace*{1.8pc}
       }}
     \def\@evenfoot{\raisebox{3pt}{%
       \hbox to 0pc{\hbox to \textwidth{{\footerpagefont\@artnum}}\hfill\mbox{}}\hspace*{1.8pc}%\hspace*{-1.8pc}
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footervolfont\@pubid}\hfill\mbox{}}}%
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footervolfont VOLUME\ \thevol, \THEYEAR}}}%
     }}
  }
% normal page
  \def\ps@headings{%
     \def\@oddhead{\parbox[t]{\textwidth}{\mbox{}\\[-6.3mm]{\raisebox{5pt}%
       {\headerfont\rightmark}}\hfill\headerlogo\mbox{}\vspace*{-3.55mm}\par%
       \rule{30.54pc}{.3pt}}}
     \def\@evenhead{\parbox[t]{\textwidth}{\mbox{}\\[-6.3mm]\mbox{}%
       \headerlogo\hfill{\raisebox{5pt}{\headerfont\leftmark}}\vspace*{-3.55mm}\par%
       \mbox{}\hfill\rule{30.54pc}{.3pt}}}
     \def\@oddfoot{\raisebox{8pt}{%
       \hbox to 0pc{\hbox to \textwidth{{\footervolfont VOLUME\ \thevol, \THEYEAR}\hfill\mbox{}}}%
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footerpagefont\@artnum}}}%\hspace*{1.8pc}
       }}
     \def\@evenfoot{\raisebox{8pt}{%
       \hbox to 0pc{\hbox to \textwidth{{\footerpagefont\@artnum}\mbox{}\hfill}}%\hspace*{1.8pc}%\hspace*{-1.8pc}
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footervolfont VOLUME\ \thevol, \THEYEAR}}}%
     }}
  }
\else
  \def\headerlogo{\raisebox{-2pt}{\includegraphics[width=7.61pc]{Logo.png}}}
  \def\headerlogoall{\raisebox{-2pt}{\includegraphics[width=7.61pc]{notaglineLogo.png}}}
  \def\ps@titlepage{%
    \def\@oddhead{\parbox[t]{\textwidth}{\mbox{}\\[-6.3mm]\mbox{}\nheaderfont\color{accessblue}\headName\hfill\headerlogo{\raisebox{-2pt}{\,}}\color{black}\vspace*{-1.5mm}\par\hrulefill}}
    \def\@evenhead{\parbox[t]{\textwidth}{\mbox{}\\[-6.3mm]\mbox{}\headerlogo\hfill\nheaderfont\color{accessblue}\headName{\raisebox{-2pt}{\,}}\color{black}\vspace*{-1.5mm}\par\hrulefill}}
     \def\@oddfoot{\raisebox{3pt}{%%
       \hbox to 0pc{\hbox to \textwidth{{\footervolfont VOLUME\ \thevol, \THEYEAR}\hfill\mbox{}}}%
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footervolfont\@pubid}\hfill\mbox{}}}%
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footerpagefont\thepage}}}%\hspace*{1.8pc}
       }}
     \def\@evenfoot{\raisebox{3pt}{%
       \hbox to 0pc{\hbox to \textwidth{{\footerpagefont\thepage}\hfill}\mbox{}}\hspace*{1.8pc}%\hspace*{1.8pc}
       \hspace*{-1.8pc}\hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footervolfont\@pubid}\hfill\mbox{}}}%
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footervolfont VOLUME\ \thevol, \THEYEAR}}}\hspace*{1.8pc}% [updated here]
     }}
  }
% normal page
  \def\ps@headings{%
     \def\@oddhead{\parbox[t]{\textwidth}{\mbox{}\\[-6.3mm]{\raisebox{-2pt}{\headerfont\rightmark}}\hfill\headerlogoall\mbox{}\vspace*{-1.5mm}\par\hrulefill}}
     \def\@evenhead{\parbox[t]{\textwidth}{\mbox{}\\[-6.3mm]\mbox{}\headerlogoall\hfill{\raisebox{-2pt}{\headerfont\leftmark}}\vspace*{-1.5mm}\par\hrulefill}}
     \def\@oddfoot{\raisebox{8pt}{%
       \hbox to 0pc{\hbox to \textwidth{{\footervolfont VOLUME\ \thevol, \THEYEAR}\hfill\mbox{}}}%
       \hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footerpagefont\thepage}}}%\hspace*{1.8pc}
       }}
     \def\@evenfoot{\raisebox{8pt}{%
       \hbox to 0pc{\hbox to \textwidth{{\footerpagefont\thepage}\mbox{}\hfill}}\hspace*{1.8pc}%\hspace*{-1.8pc}
       \hspace*{-1.8pc}\hbox to 0pc{\hbox to \textwidth{\mbox{}\hfill{\footervolfont VOLUME\ \thevol, \THEYEAR}}}\hspace*{1.8pc}% [updated here]
     }}
  }
\fi
\pagestyle{headings}
\makeatother
% FIX for VOLUME AND YEAR END HERE

A: Open the latex class ieeeaccess, find the 2016 and change it to 2020

A: To remove VOLUME 4,2016 from the Access template. Edit ieeeaccess.cls file. Open the file and search for VOLUME, the value of volume(eg: 4), and value of year (eg:2016). Remove all these values from the ieeeaccess.cls file. This works!


text:
Q: Is it possible to create a custom cursor using PyQt? I wanted to use a bigger version of the crosshair cursor for my program but it seems like i can't change the specs of the standard cursor shapes (e.g. QtCore.Qt.OpenHandCursor). That said, is it possible for me to create a customized version of a cursor instead? Like say, from a png image of a cursor?

A: The image should be opened first using PIL, converted to bitmap and then instantiated as a cursor.
here's the code:

 from PIL import Image
    from PIL.ImageQt import ImageQt
    img = Image.open('cursor.png')
    imgQ = ImageQt(img)
    cursorBitmap = QtGui.QBitmap.fromImage(imgQ)
    CURSOR_NEW = QtGui.QCursor(cursorBitmap)

edit: as @ekhumoro pointed out in the comments, it can be achieved by using Pixmap and combining it with QCursor, so it'd look like:
CURSOR_NEW = QtGui.QCursor(QtGui.QPixmap('cursor.png'))

if this causes an error it might be because the code cannot find the correct file, so the proper path might need to be added to the code


text:
Q: GridView Editing when bound to a Datatable (no database) I am a beginner at ASP.NET and I have been trying to allow editing/updating of a GridView that is bound to a Datatable, without apparent success.
The GridView, named "WeightGridView", has two columns, "Asset Class" and "Weight", and is populated upon the click of a button "AddAssetsButton". Once you click on this button, the GridView will be populated with the values of a listbox, "ListBox2". The code for this event handler is:
 protected void AddAssetsButton_Click(object sender, EventArgs e)
 {
        DataTable table = new DataTable();
        table.Columns.Add("Asset Class", typeof(string));
        table.Columns.Add("Weight", typeof(double));
        foreach (ListItem li in ListBox2.Items)
        {
            DataRow dr = table.NewRow();
            dr["Asset Class"] = li.Value;
            dr["Weight"] = 0;
            table.Rows.Add(dr);
        }
        WeightGridView.DataSource = table;
        WeightGridView.DataBind();
        SelectAssetsButton_ModalPopupExtender.Hide();
 }

I have created a RowEditing and RowUpdating functions for the GridView, but they don't seem to work properly.
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            WeightGridView.DataBind();
        }
    }

    protected void WeightGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        WeightGridView.EditIndex = e.NewEditIndex;
    }

    protected void WeightGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string weight;
        weight = ((TextBox)WeightGridView.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
        WeightGridView.EditIndex = -1;
        WeightGridView.DataBind();
    }

Should you need any additional code to answer this post, please let me know and I will update the post.
Any help will be appreciated! Thank you!


text:
Q: Empty path/file not found I am having a problem with writing text to a file. This is my code:
string[] data = { "[Civilisation Manifest ?.1]", "#Structure: ", "#Gold:" };

string path = Properties.Resources.save;
System.IO.File.WriteAllLines(path, data);

And the exception I am having is that An empty path cannot be used.
What am I doing wrong?

A: What is the value of the path variable? The error message implies it is empty. Sorry for stating the obvious.
Path must be full path and folder. c:\temp\myfile.txt for example.

A: It looks like the value of Properties.Resources.save is not set.

*

*Open the Properties of your project.

*Go to tab "Resources"

*Probably there is a resource "save", but no value set for it, like here:

*

*Set the value to the path to your save file, for example "C:\temp\mysave.txt".

P.S.: The point of resources mostly is to read data out of them, not to write data into them. For example, they will be copied to the build result folder or embedded directly into the .dll, so you can't really write to them anyway. For writing out a save file, resources are therefore probably not what you want to use; Just create a new file directly instead. (The path to that file, being a hardcoded string, can be stored as a resource as shown above.)


text:
Q: Integrating AngularJS 1.2 into existing MVC site I currently have an existing ASP MVC4 application that returns views (razor) from controllers and would like to start transitioning the application into a SPA (single page application) using web api and angular js.  My question is can i slowly start transitioning specific views/urls to be routed by angular and have other views/urls call back to the legacy controllers in the MVC application that render razor views?  For example I have my main angular js file stating the following
window.EcentralSPA = angular.module('EcentralSPA', ['ngRoute']);

EcentralSPA.config(['$routeProvider', function ($routeProvider) {
  $routeProvider.when('/users', {
    templateUrl: 'app/views/users.html',
    controller: 'UsersController'
  });
}]);

EcentralSPA.controller('UsersController', ['$scope', function ($scope) {
  //TODO
}]);

Basically i'd just like the /users url to get handled by angular and the rest of the urls to call back to the web server to the correct mvc controller and render back the razor view.  However with my current configuration above all calls to anything besides /users returns empty data.  Any suggestions?  Thank you.

A: If you decide part of application is SPA and another is not for some url, you need to then stop AngularJS from intercepting url changes. For this when you render  tags use one of the following ways to ignore angularjs routing

*

*Links that contain target element. Example: link

*Absolute links that go to a different domain. Example: link

*Links starting with '/' that lead to a different base path when base is defined. Example: link
See the location documentation for more details.
Also i don't think you can then perform navigation using $route or $location service for urls that you want to handle outside angularjs.
Full page refresh will always cause the full framework to reload for all AngularJS SPA pages.


text:
Q: Replace a digit in a string with a symbol The following code reads and finds the digit 1. My question is how could it be replaced with a symbol (say 'a') and printed back with the replaced ones.
int i, newtxt;
    char text[100];
    printf("Enter text: ");
    gets(text);
    for(i = 0; i<strlen(text); i++)
    {
        if(text[i] == '1')
            replace with a?
    }
    printf("%s", newtxt);
    getch();
    return 0;
}

A: Try this
if(text[i] == '1')
        text[i] = 'a';

And do not use gets. Its unsafe. Use fgets instead.
fgets(text, 100, stdin);

Also
printf("%s", newtxt);

is wrong. You have to fix this (try it your self).

A: Just replace it like this:
 if(text[i] == '1')
     text[i] = 'a';


text:
Q: How do I use find to copy and remove extensions keeping the same subdirectory structure I'm trying to copy all the files from one directory to another, removing all file extensions at the same time.
From directory 0001:
 0001/a/1.jpg
 0001/b/2.txt

To directory 0002:
 0002/a/1
 0002/b/2

I've tried several find ... | xargs c...p with no luck.

A: Recursive copies are really easy to to with tar. In your case:
tar -C 0001 -cf - --transform 's/\(.\+\)\.[^.]\+$/\1/' . |
tar -C 0002 -xf -

A: If you haven't tar with --transform this can works:
TRG=/target/some/where
SRC=/my/source/dir
cd "$SRC"
find . -type f -name \*.\* -printf "mkdir -p '$TRG/%h' && cp '%p' '$TRG/%p'\n" |\
   sed 's:/\.::;s:/./:/:' |\
   xargs -I% sh -c "%"

No spaces after the \, need simple end of line, or you can join it to one line like:
find . -type f -name \*.\* -printf "mkdir -p '$TRG/%h' && cp '%p' '$TRG/%p'\n" | sed 's:/\.::;s:/./:/:' | xargs -I% sh -c "%"

Explanation:

*

*the find will find all plain files what have extensions in you SRC (source) directory

*the find's printf will prepare the needed shell commands:

*

*command for create the needed directory tree at the TRG (target dir)

*command for copying

*the sed doing some cosmetic path cleaning, (like correcting /some/path/./other/dir)

*the xargs will take the whole line

*and execute the prepared commands with shell

But, it will be much better:

*

*simply make an exact copy in 1st step

*rename files in 2nd step

easier, cleaner and FASTER (don't need checking/creating the target subdirs)!

A: Here's some find + bash + install that will do the trick:
for src in `find 0001 -type f`  # for all files in 0001...
do
  dst=${src/#0001/0002}         # match and change beginning of string
  dst=${dst%.*}                 # strip extension
  install -D $src $dst          # copy to dst, creating directories as necessary
done

This will change the permission mode of all copied files to rwxr-xr-x by default, changeable with install's --mode option.

A: I came up with this ugly duckling:
find 0001 -type d | sed 's/^0001/0002/g' | xargs mkdir
find 0001 -type f | sed 's/^0001//g' | awk -F '.' '{printf "cp -p 0001%s 0002%s\n", $0, $1}' | sh

The first line creates the directory tree, and the second line copies the files.  Problems with this are:

*

*There is only handling for directories and regular files (no
symbolic links etc.)

*If there are any periods (besides the
extension) or special characters (spaces, etc.) in the filenames
then the second command won't work.


text:
Q: Storing locations in hierarchy - How to overcome? This is my schema for storing locations:
CREATE TABLE locality (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR (100) NOT NULL UNIQUE,
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17)
);

CREATE TABLE administrative_area_level_1 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR (100) NOT NULL UNIQUE,
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17)
);

CREATE TABLE administrative_area_level_2 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR (100) NOT NULL UNIQUE,
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17)
);

CREATE TABLE administrative_area_level_3 (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR (100) NOT NULL UNIQUE,
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17)
);

CREATE TABLE country (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR (100) NOT NULL UNIQUE,
iso VARCHAR (3) NOT NULL UNIQUE,
loc VARCHAR (255) NOT NULL,
rad VARCHAR (255)
);

Since they are a hieracy I want to link them together. For example:
USA ----> country(id=1)
Washington ----> administrative_area_level3(id=54), country(id=1)

My issue is with this is that if I try to daisy chain the tables like this:

locality -> administrative_area_level_1 -> administrative_area_level_2
  -> administrative_area_level_3 etc

Then adding an entry like "Washington, USA" before adding "USA" will cause USA to be added. This is from a google geocode but that original geocode will only gives me the co-ordinate values of Washington and not that of "USA" generally. I would need to make a second geocoding request for USA and add these values separately.
My only option as far as I see is do something like this:

*

*See if Washington is in table already

*Geocode Washington

*Add results to administrative_area_level2 and country

*If country did not exist, geocode country and add "loc" coordinates

Is there a better or smarter way of doing this?

A: Let me say right up front that if you're working with hierarchies in a relational database, you really want this book:  http://www.amazon.com/Hierarchies-Smarties-Edition-Kaufmann-Management/dp/0123877334
Thinking about your Washington question, I'm wondering:  Are you unhappy because your table structure forces you to add an entry for "USA" when all you really want is "Washington?"
I'm not 100% I can answer your question, but let me tell you how I approach these types of problems.  I almost always model hierarchies in relational databases using paths.  Instead of 5 tables, I'd have one called "locations," which would look something like this:
create table locations (
    id varchar(10) not null primary key,
    path varchar(1000) not null unique,
    name varchar(40) not null,
    loc varchar(255) not null, -- from your model
    rad varchar(255) not null, -- from your model
);

"id" is a short identifier for each location, and "path" describes this location's position in the hierarchy in terms of its id and and ids of other locations.
So Washington would look like this:
id: wa
path: na/usa/wa
name: Washington

We're saying that Washington ("wa") is part of the USA ("usa") which is part of North America ("na").
Now at this point you can choose whether you want to actually include rows for "usa" and "na" or not.  You don't have to have rows for them in order to insert your "wa" row.  You could either insert the rows immediately, or never insert them (and just have your code understand that "wa" can be part of "usa" without "usa" being fully defined), or not insert them right away and have some job periodically run and add rows for any locations that appear in paths but don't have their own rows.
The Hierarchies book I reference above covers this path strategy in detail and includes lots of SQL code showing you how you can manipulate and browse the hierarchy.


text:
Q: How to read $A=[0,1]\times[a,5]$ I have this problem: consider the two sets $A$ and $B$
$$A=[0,1]\times [a,5]$$ and $$B=\{(x,y):x^2+y^2<1\}$$
What are the values of $a$ that guarantee the existence of a hyperplane that separates $A$ from $B$.
Given a chosen value of $a$, find one of those hyperplanes.
My main problem is axiomatics: how do I read: $A=[0,1]\times[a,5]$, what's with the $\times$?
Thank you

A: $[0,1]\times[a,5]$ is the Cartesian product of the intervals $[0,1]$ and $[a,5]$:
$$[0,1]\times[a,5]=\big\{(x,y):0\le x\le 1\text{ and }a\le y\le 5\big\}\;.$$
More generally, for any sets $A$ and $B$,
$$A\times B=\big\{(a,b):a\in A\text{ and }b\in B\big\}\;.$$

A: The $\times$ stands for cartesian product, i.e. $X\times Y=\{(x,y)\mid x\in X, y\in Y\}$.
Whether ordered pairs $(x,y)$ are considered a basic notion or are themselves defined (e.g. as Kurtowsky pairs) usually does not matter. See alo here.


text:
Q: ng-repeat array from json file I'm very new to AngularJS, and have tried to find an answer to my following question around the web.
So my issue is as follows:
I have a handler (.ashx) file on my site. The handler returns a JSON array. It's located on the following URL: /services/returnsites.ashx
It's a quite simple JSON aray that looks like this:
[{"NodeId":a93064,"NodeName":"Planes"},{"NodeId":a49856,"NodeName":"Bicycles"},{"NodeId":a19631,"NodeName":"Cars"}]

I'd like to loop through each of the sites in the json array.
I have an html-file containing this:

            {{site.NodeName}} - {{site.NodeId}}

I have a controller as well, looks like this:
angular.module("umbraco").controller("My.Controller", function($scope) {
   ...
});

What I need is to put something instead of the trhee dots to grab the array from the json file.
I can get it working if I my controller looks like this (containing the array the controller file):
angular.module("umbraco").controller("My.Controller", function($scope) {
    $scope.sites = [
    {
        NodeName: "Planes",
        NodeId: "a93064"
    },
    {
        NodeName: "Bicycles",
        NodeId: "a49856"
    },
    {
        NodeName: "Cars",
        NodeId: "a19631"
    }
    ];
});

But I can't get it working if I'm trying to grab the array from the file on the server. I've tried a couple of different things including something like the $hhtp.get() etc. copied from around the web, but nothing seems to work :(
I hope that someone can help me out.
Thank you very much in advance.
/Kim

A: First of all, your backend's JSON response is not well formatted. NodeId values have to be string, as they contain non-numeric characters.
[{
    "NodeId": "a93064",
    "NodeName": "Planes"
}, {
    "NodeId": "a49856",
    "NodeName": "Bicycles"
}, {
    "NodeId": "a19631",
    "NodeName": "Cars"
}]

After fixing that, you just need to use $http get method to make backend request.
.controller('My.Controller', function($scope, $http) {
    $http.get('returnsites.ashx').success(function(sites) {
      $scope.sites = sites;
    });
});

Here is a working plunker.

A: An $http.get() should do the trick. Try:
$scope.sites = [];

$http.get('/services/returnsites.ashx').success(function(data) {
    $scope.sites = data;
});


text:
Q: three congruent circles intersect each other, bounding two shaded regions
Three circles of the same radius intersect other so that the center of one circle is on the circumference of the others, as shown. I want to draw this shading with tikz.

A: Just for reference:
\documentclass[tikz,border=5]{standalone}
\tikzset{random fill/.code={%
\pgfmathsetmacro\r{rnd}\pgfmathsetmacro\g{rnd}\pgfmathsetmacro\b{rnd}%
\definecolor{.}{rgb}{\r,\g,\b}%
\tikzset{fill=.}}}
\begin{document}
\begin{tikzpicture}[every path/.style={random fill}]
\path (0:0)   arc (150:90:1)  arc (30:150:1)  arc (90:30:1) -- cycle;
\path (0:0)   arc (30:-30:1)  arc (210:150:1) -- cycle;
\path (150:1) arc (90:330:1)  arc (270:150:1) -- cycle;
\path (30:1)  arc (90:-150:1) arc (270:390:1) -- cycle;
\path (0:0)   arc (30:90:1)   arc (150:270:1) arc (210:150:1) -- cycle;
\path (0:0)   arc (150:90:1)  arc (30:-90:1)  arc (-30:30:1)  -- cycle;
\end{tikzpicture}
\end{document}

A: \documentclass[border=5pt]{standalone}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
   \coordinate (Y) at (0,0);
   \coordinate (X) at (210:2.5cm);
   \coordinate (Z) at (-30:2.5cm);
   \fill[gray]  (X) circle (2.5cm);
   \fill[white] (Y) circle (2.5cm);
   \begin{scope}
      \clip  (Z) circle (2.5cm);
      \fill[gray]  (X) circle (2.5cm);
   \end{scope}

   \foreach \pt in {X,Y,Z} {
     \draw (\pt) circle (2.5cm);
     \fill[black]  (\pt) circle (2pt);
   }
\end{tikzpicture}

\end{document}

A: With tkz-euclide just to show variety:
\documentclass[border=5pt]{standalone}

\usepackage{tkz-euclide}
\usetikzlibrary{backgrounds}
\usetkzobj{all}

\begin{document}
  \begin{tikzpicture}[background rectangle/.style={fill=pink!40},
                        show background rectangle,rotate=-10]
     \tkzDefPoint(0,0){Y}
     \tkzDefPoint(210:2){X}
     \tkzDefPoint(-30:2){Z}
     \tkzFillCircle[color=gray!40](X,Y)
     \tkzFillCircle[color=white](Y,X)
     \begin{scope}
       \tkzClipCircle(Z,Y)
       \tkzFillCircle[color=gray!50,%
          opacity=.5](X,Y)
     \end{scope}
     \tkzDrawCircle(X,Y)
     \tkzDrawCircle(Y,X)
     \tkzDrawCircle(Z,Y)
     \tkzDrawPoints[color=blue,fill=blue](X,Y,Z)
     \tkzLabelPoints[right](X,Y,Z)

  \end{tikzpicture}
\end{document}


text:
Q: React TypeError: undefined onSubmit I get an undefined error in the following the clicking of the submit button in a login page. Here is the Login.js file:
import React, {Component} from 'react'
import { login } from './StudentFunctions'

class Login extends Component {
  constructor() {
    super()
    this.state = {
      email: '',
      password: '',
      errors: {}

    }

    this.onChange = this.onChange.bind(this)
    this.onSubmit = this.onSubmit.bind(this)
  }

  onChange(e) {
    this.setState({ [e.target.name]: e.target.value })
  }

  onSubmit(e) {
    e.preventDefault();

    const student = {
      email: this.state.email,
      password: this.state.password
    }

    login(student).then(res => {
      if (!res.error) {
        this.props.history.push('/profile')

      }
    })
  }
  render() {
    return (

            <form noValidate onSubmit={this.onSubmit}>

Please sign in

                Email Address
                <input type="email"
                  className="form-control"
                  name="email"
                  placeholder="Enter email"
                  value={this.state.email}
                  onChange={this.onChange}
                />

                  Password
                  <input type="password"
                    className="form-control"
                    name="password"
                    placeholder="Enter Password"
                    value={this.state.password}
                    onChange={this.onChange}
                  />

                <button type="submit"
                className="btn btn-lg btn-primary btn-block">
                  Sign in
                </button>
              </form>

    )
  }
}

export default Login

And the function imported from StudentFunctinos.js is

export const login = student => {
  return axios
  .post('/TPMS/api/v1.0/student/login', {
    email: student.email,
    password: student.password

  })
  .then(res => {
    localStorage.setItem('usertoken', res.data)
    console.log(res)
    return res.data
  })
  .catch(err => {
    console.log(err)
  })
}

The error is saying that e is undefined in the Login.js file, which throws the catch error. Is it because in the button html there is no declaration of what happens on the click:
i.e onClick(e) => {this.onSubmit}
or something like this?

A: The problem is, you applied the normal class method, which is handling this in a different way. it considers this with the context you call it, so in your case, you call it in an event binding(onSubmit), so it will not consider itself in the class and it will return undefined. My solution is using arrow functions, which uses this in a stable way, and always executes in the lexical scope, in this case, in the Class you call:
  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value })
  }

  onSubmit = (e) => {
    e.preventDefault();

    const student = {
      email: this.state.email,
      password: this.state.password
    }

    login(student).then(res => {
      if (!res.error) {
        this.props.history.push('/profile')

      }
    })
  }

you can find more explanations in this question: Difference between class object Method declaration React?
Also, I suggest this tutorial, which explains a lot about Javascripts unusual behaviors:
Javascript the weird parts

A: onSubmit = (e) => {
    e.preventDefault();
    const { email, password } = this.state;
    const student = {email, password}

    login(student).then(res => {
      if (!res.error) {
        this.props.history.push('/profile')

      }
    })
  }


text:
Q: How to print the entire row for particular time interval using python I need to get the starttime and endtime from user.Then i need to print the entire row of starttime to end time.
Below is the data available in 'xsss.csv' file
aaaaa   lshds   aaaaa   aaaaa   5:18    ss
dslkd   lsh2ds  dslkd   dslkd   5:19    dd
lshds   lshds   lshds   lshds   5:20    dd
aaaaa   aaaaa   aaaaa   aaaaa   5:21    dase
dslkd   dslkd   dslkd   dslkd   5:22    daew
lshds   lshds   lshds   lshds   5:23    sare
aaaas   aaaas   aaaas   aaaas   5:24    ddd
dslkd   dslkd   dslkd   dslkd   5:25    dss
d hdd   d hdd   d hdd   d hdd   5:26    dfsgdsg
ddddd   ddddd   ddddd   ddddd   5:26    dsdf
wswsx   wswsx   wswsx   wswsx   5:27    dw
swswq   swswq   swswq   swswq   5:28    ff
If starttime=5:18 and endtime= 5:20.Then output should print like below
aaaaa lshds aaaaa aaaaa 5:18 ss
dslkd lsh2ds dslkd dslkd 5:19 dd
lshds lshds lshds lshds 5:20 dd
The code snippet:
import os,csv,datetime
from datetime import datetime
starttime=datetime.strptime(raw_input('start time:' ),"%H:%M")
endtime=datetime.strptime(raw_input('end time:' ),"%H:%M")
print starttime
print type(starttime)
with open('csvv.csv') as d:
 line =d.readlines()

 print "ell"

 for line in d:

     print  "jjj"

     if row == starttime and endtime:

         print row


text:
Q: repeated-measures ANOVA By calculating a repeated-measures ANOVA, no partial eta squared is listed in the table and I can't calculate any post-hoc tests.
Does anybody know possible reasons for this?
Thank you very much!


text:
Q: How to make a combined gestures? I want to ask some interesting thing.
I want my app can action when a custom combined gestures occur.
For example:
call a action(/method) when user swipe left, top, left without the finger leave on the screen.
How can i make this custom gesture?
and second question is can i swipe upper left( like " / " this direction)?
How to make this gesture?
can anyone one help me? please! thanks

A: Well, conceptually you need to subclass UIGestureRecognizer, do some position tracking, and make use of the fact that after importing UIGestureRecognizerSubclass.h the gestures state property becomes read/write to move all the gears around yourself. As and example, I'll include a basic prototype for a diagonal gesture that I tried to build a long time ago. (It needs a few kinks worked out, but overall, it works.)
.H
#import <UIKit/UIKit.h>
#import <UIKit/UIGestureRecognizerSubclass.h>

@interface MMDiagnoalSwipeGestureRecognizer : UIGestureRecognizer
@property (nonatomic, readwrite) BOOL shouldReverseYDelta;
@property (nonatomic, readwrite) CGFloat tolerance;
@property (nonatomic, readonly) CGFloat angleOfSwipe;
@end

.M
#import "MMDiagnoalSwipeGestureRecognizer.h"
@interface MMDiagnoalSwipeGestureRecognizer ()
@property (nonatomic, readwrite) CGPoint startingPoint;
@end

@implementation MMDiagnoalSwipeGestureRecognizer

- (id)initWithTarget:(id)target action:(SEL)action {
    self = [super initWithTarget:target action:action];
    if (self) {
        _shouldReverseYDelta = NO;
        _tolerance = 30.0f;
    }
    return self;
}

- (CGFloat)angleOfGestureFromPoint:(CGPoint)start toEndPoint:(CGPoint)end {
    CGFloat deltaY = (_shouldReverseYDelta) ? end.y - start.y : start.y - end.y;
    CGFloat deltaX = end.x - start.x;

    _angleOfSwipe = atan2f(deltaY, deltaX) * 180.0f / M_PI;

    return _angleOfSwipe;
}

- (CGFloat)diagonalDistanceFromPoint:(CGPoint)start toEndPoint:(CGPoint)end {
    CGFloat deltaX = fabsf(start.x - end.x);
    CGFloat deltaY = fabsf(start.y - end.y);

    CGFloat hypotenuse = powf(deltaX, 2.0f) + powf(deltaY, 2.0f);

    return sqrtf(hypotenuse);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (touches.count > 1) {
        if (self.state == UIGestureRecognizerStatePossible) {
            self.state = UIGestureRecognizerStateFailed;
        }
    }else{
        [touches enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
            UITouch *touch = (UITouch *)obj;
            _startingPoint = [touch locationInView:self.view];
        }];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    [touches enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
        UITouch *touch = (UITouch *)obj;
        CGPoint endPoint = [touch locationInView:self.view];
        CGFloat angle = [self angleOfGestureFromPoint:_startingPoint toEndPoint:endPoint];

        if (self.state == UIGestureRecognizerStatePossible) {
            if ([self angleIsWithinDiagonalTolerance:angle] == YES) {
                if ([self diagonalDistanceFromPoint:_startingPoint toEndPoint:endPoint] >= 20.0f) {
                    self.state = UIGestureRecognizerStateRecognized;
                }
            }else{
                self.state = UIGestureRecognizerStateFailed;
            }
        }
    }];
}

- (BOOL)angleIsWithinDiagonalTolerance:(CGFloat)angle
{
//    NSLog(@"%s",__PRETTY_FUNCTION__);
    NSAssert1(_tolerance < 45.0f, @"DiagonalSwipeGestureRecognizer Error: tolerance property must be set to a value less than 45.0f. Otherwise, the gesture will be detected at any angle. If you don't care and want the swipe to be recognized at any angle, remove the NSAssert call from - %s.", __PRETTY_FUNCTION__);
//    NSAssert(_tolerance < 45.0f, @"DiagonalSwipeGestureRecognizer Error: tolerance property must be set to a value less than 45.0f. Otherwise, the gesture will be detected at any angle. If you don't care and want the swipe to be recognized at any angle, remove the NSAssert call from -[MMDiagnoalGestureRecognizer angleIsWithinDiagonalTolerance:].");

    if (angle >= 45.0f - _tolerance && angle <= 45.0f + _tolerance) {
        return YES;
    }else if (angle <= - (45.0f - _tolerance) && angle >= - (45.0f + _tolerance)) {
        return YES;
    }else if (angle >= 135.0f - _tolerance && angle <= 135.0f + _tolerance) {
        return YES;
    }else if (angle <= - (135.0f - _tolerance) && angle >= - (135.0f + _tolerance)) {
        return YES;
    }else{
        return NO;
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self touchesEnded:touches withEvent:event];
    self.state = UIGestureRecognizerStateChanged;
}

- (void)reset {
    //don't call, will be called automatically.
}

@end


text:
Q: SQL.sql: Error (4,1): ORA-01951: ROLE 'CUSTOM_MASTER_ROLE' not granted to 'OPS$DOMAIN\USER' I am using someone else's database and if I try to revoke a custom role it fails with an ORA-01951 if the user does not have the role.
SQL.sql: Error (4,1): ORA-01951: ROLE 'CUSTOM_MASTER_ROLE' not granted to 'OPS$DOMAIN\USER'
How can I check in the SQL so I only try to remove the role if the user has the role?
The role creation is in a package I do not have the source code to so I do not know exactly how they created the role in the first place.

A: I managed to create this code to do it.
declare
  hasRole number(1);
  v_sql varchar2(500);
begin
  select case
           when exists(select 1 from DBA_ROLE_PRIVS where
           grantee = 'OPS$DOMAIN\USER' and
           granted_role = 'CUSTOM_MASTER_ROLE')
         then 1
         else 0
       end  into hasRole
  from dual;

  if (hasRole=1) then
    v_sql := 'revoke CUSTOM_MASTER_ROLE from "OPS$DOMAIN\USER"';
    execute immediate v_sql;
  end if;
end;

Hope it helps someone else.

A: Your query works but a bit complicated. I would use
For aRow in (select * from
       DBA_ROLE_PRIVS where
       grantee = 'OPS$DOMAIN\USER'
       and granted_role = 'CUSTOM_MASTER_ROLE')
LOOP
   v_sql := 'revoke CUSTOM_MASTER_ROLE from "OPS$DOMAIN\USER"';
   execute immediate v_sql;
END LOOP;


text:
Q: Should I process a large amount of data with SQL or Ruby? I have a MySQL table with hundreds of thousands of entries in it.
I need to specify a date range and select all the entries between those two dates. I then need to break down the entries hour by hour and obtain a specific field.
Use Case:
I would need an hour-to-hour breakdown of the entries from June 6 to June 12. So, on June 6th I would need an array of entries from 12am to 1am, 1am to 2am, 2am to 3am, etc.
Which is faster? (and why!):

*

*Running 144 SQL queries to SELECT device_id FROM entries WHERE updated_at >= sometime AND  updated_at <= sometime+1.hour where sometime is something like 12pm to 1pm, and then 1pm to 2pm, etc.

*Running 1 SQL query to SELECT device_id FROM entries WHERE updated_at >= start_date AND  updated_at <= end_date to get all the entries within the entire time period, and then use ruby to group the entries down by hour.
If anyone has any resources on why ruby or MySQL might be faster for this type of stuff, it would be much appreciated. Would like to do some reading.

A: SQL databases are built for such operations. Use them! You can always do some benchmarks but the results seem very predictable to me.

A: I think the best way to do that is to have a updated_at_month, updated_at_day, updated_at_hour (TINYINT - as all values are very small) INDEXED fields when you insert the log, and then select the range and group by like that:
select device_id FROM logs where updated_at BETWEEN sometime AND some_other_time group by updated_at_month, updated_at_day, updated_at_hour

I assume updated_at is indexed field.
or
select device_id FROM logs where updated_at_month=6 and updated_at_day>=6 and updated_at_day<=12 group by updated_at_day, updated_at_hour

But, how many rows are we talking about in total?
And as i noticed you select device_id field from that without any counts...or groups...perhaps you should select device_id, updated_at_day,updated_at_hour, count(*) as times


text:
Q: Passing value PHP (Online Cart) So I am making a php page where it will receive all the data from the previous php page. I have already displayed the list of the products but everytime I click the add to cart button, it only reads the quantity of the last product.
while($row=mysql_fetch_array($result)) {
$dib = $row['db_prod_id'];
$Item_ID =$row['bbs_prod_id'];
$Item_Name =$row['prod_name'];
$Item_Description =$row['description'];
    $Price =$row['price'];
$Item_Image =$row['item_image'];

echo "<input type='hidden' name='dib' value='$dib'>";
echo "<input type='hidden' name='id' value='$Item_ID'>";
echo "<input type='hidden' name='name' value='$Item_Name'>";
echo "<input type='hidden' name='desc' value='$Item_Description'>";
echo "<input type='hidden' name='price' value='$Price'>";
echo "<input type='hidden' name='img' value='$Item_Image'>";

echo "
";
echo "$Item_ID	";
echo "$Item_Name	";
echo "$Item_Description	";
echo "$Price	";
echo "	";
echo "<input type='text' value='' placeholder='how many' name='quantity'>";

echo "<input type='submit' value='Add to Cart'>	";
echo "
";

I only test the passing of quantity.
Only the last item echoes a quantity.
session_start();

$user = $_SESSION['bbs_buyer_login'];

require("dbconnect.php");

$quantity = $_POST['quantity'];

echo "$quantity";

I already have 3 items on my list but only the third item echoes a quantity and is only being read everytime I click the 'add to cart' button.
Help please. Thank you!

A: You're inside loop. Change your input to be treated as array:
echo "<input type='text' value='' placeholder='how many' name='quantity[]'>";

Then $_POST['quantity'] will be an array with quantities. You can lookup this via
print_r($_POST['quantity']);

or
var_dump($_POST['quantity']);

I don't know how rest of your code works, but it should do the trick in this case.

A: $_POST derives from the HTTP request you're sending to the server containing an array key => value of the name and value of the inputs.
To store the quantity and later add to it, you need to use your cookies/sessions. Firstly, instance the cart array like this:
if(!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

You can then set the product id ($pid) and the quantity ($q) in this array like this:
if(isset($_POST['quantity']) && isset($_POST['id']) {
    $q = $_POST['quantity'];
    $pid = (int) $_POST['id'];
    $c = $_SESSION['cart'];
    $c[$pid] = $c[$pid] ? $c[$pid] + (int) $q : (int) $q;
    $_SESSION['cart'] = $c;
}

Then, to later see the products to their quantity simply run an SQL query on each product.
foreach($_SESSION['cart'] as $pid => $q) {
    // change SQL to meet your DB
    $sql = 'SELECT * FROM products WHERE product_id = :product_id LIMIT 1';
    $stmt = $pdo->Prepare($sql); // using PDO driver
    $stmt->bind_param(':product_id', (int) $pid); // dont trust the data
    $stmt->execute();
    $r = $stmp->fetch();
    $cost = $r['price'] * $q; // get the price and multiply by quantity
}


text:
Q: Snowflake SQL error - Invalid argument types for function '-': (TIMESTAMP_NTZ(9), TIMESTAMP_NTZ(9)) I get this error when I try to subtract the timestamps and do a window function (lead, lag and partition by):

Invalid argument types for function '-': (TIMESTAMP_NTZ(9), TIMESTAMP_NTZ(9))

Tried date_diff, but that doesn't work along with window function
SELECT
   user_id,
   event,
   received_at,
   received_at - LAG( received_at,1) OVER (PARTITION BY user_id ORDER BY received_at) AS last_event
FROM
   segment_javascript.help_center_opened

A: You can't do it the "Oracle way" by just subtracting two dates to get a number, you must use a diff function with a unit/scale of measure, eg:

SELECT
   ts,
   TIMESTAMPDIFF(MILLISECONDS, LAG(ts, 1) OVER (ORDER BY ts), ts) tsd
FROM
   (VALUES (CURRENT_TIMESTAMP), (DATEADD(DAY, 1, CURRENT_TIMESTAMP))) v(ts);

A: I suppose that you need to calcuate the time difference for the same user_id with last event received time.
If so, I think this would work:
SELECT
   user_id,
   event,
   received_at,
   DATEDIFF(
     MINUTE, -- or any other supported date/time part
     received_at, -- start time
     LAG( received_at,1) OVER (PARTITION BY user_id ORDER BY received_at) -- end time
     ) AS last_event
FROM
   segment_javascript.help_center_opened


text:
Q: How to prevent java.net.UnknownHostException using org.snmp4j.transport.DefaultUdpTransportMapping How do I avoid the UnknownHostException in this line:
TransportMapping transport = new DefaultUdpTransportMapping();

I use the SNMP4J 2.2.0 API and use multiple threads (one thread for each switch)

A: OK I got this fixed by calling
TransportMapping transport = new DefaultUdpTransportMapping();

only once for each thread. With 50 threads it still works fine.
My guess is that the networkIf / OS / Java was out of available ports


text:
Q: NullInjectorError: No provider for NgbModalRef I try to use NgbModalRef to close a Modal (That open with NgbModal) and in some components I see the Error:
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(MyModule)[NgbModalRef -> NgbModalRef -> NgbModalRef -> NgbModalRef -> NgbModalRef]:
NullInjectorError: No provider for NgbModalRef!

Note1:I have imported and Injected NgbModalRef and NgbModal in my component and tried using NgbModule in my appModule and it didnt Work!
Note2:I saw somewhere that people say to write NgbModalRef in appModule provider,and i dont think its the right way because its not a Service!!
Can anyone please help..

A: i solved this problem using this reference.
https://github.com/ng-bootstrap/ng-bootstrap/issues/1832#issuecomment-331798666
from  private modalReference: NgbModalRef;
to   private modalReference: any;


text:
Q: MobaXterm - Why is my LOG filename shows "localhost" instead of my hostname when establishing an SSH session? I'm quite new with MobaXterm. For each SSH session that I open to a given host, I want to log the terminal output to an individual file whose filename includes the given hostname + timestamp. I have thus setup my MobaXterm terminal settings with "&H_&Y-&M-&D-&T" as log filename, where "$H" is a variable standing for "hostname".
It works as a charm when opening a new session by clicking on "Session" icon from MobaXterm's GUI then select "SSH" and manually provide the hostname's FQDN I want to connect to.
Example:
Session -> SSH -> Remote host: "MyNas.MydomainName"
==> Log file name is properly set to "MyNas.MydomainName_2022-01-07-113521.log"
However, if I open a similar session from windows's command line prompt, the log filename's hostname part is set to "localhost", instead of my hostname.
Example:
C:\Program Misc\MobaXterm>MobaXterm_Personal_21.5.exe -newtab "ssh MyNas.MydomainName"
==> Log file name is wrongly set to "localhost_2022-01-07-113521.log"
Any insight ? Many thanks in advance for helping.

A: Because then the SSH connection isn't made by MobaXterm itself – it's made by a local command that runs inside the launched MobaXterm "local" session.
The ssh command invokes a standalone OpenSSH client (the Cygwin-based build that comes with MobaXterm, not the native version that comes with Windows). It seems to be a customized version that has some integration (for the file panel), but the app still treats it as a command running inside a local shell.
Meanwhile when you create an SSH session through the GUI, that doesn't use OpenSSH – it uses MobaXterm's own internal SSH code (which is copied from PuTTY).
There seems to be no way to create new SSH sessions through the command line, only load existing saved sessions.


text:
Q: Space between header and menu on Tumblr blog I recently made some changes to my Optica themed blog on Tumblr; specifically, I changed the height of the header image in the custom css section. Problem is, now I have this huge space between the header and the menu which I can't get rid of. I tried removing parts from the source, but to no avail.
You can see the blog here: http://ilconfess.tumblr.com

A: You have your height set to 350px in your css.
Check main.css line 539 and set height to Auto.


text:
Q: If $X$ follows an $\operatorname{Exp}(\theta)$, does $1/X$ follow an $\operatorname{Exp}(1/ \theta)$? I heard a teacher say that if $$X \sim \operatorname{Exp}(\theta)$$
then $$\frac{1}{X} \sim \operatorname{Exp}\left(\frac{1}{\theta}\right)$$
I don't trust this teacher because he has given us wrong answers before.
I tried to obtain this myself:
If $y = g(x) = \frac{1}{x}$, then $$f_Y(y) = f_X(g^{-1}(y)) \cdot \left|\frac{d}{dy}g^{-1}(y)\right|$$
$$f_Y(y) = \theta \cdot e^{-\theta/y} \cdot \frac{1}{y^2}$$
where $1/y \in (0, +\infty)$.
I don't see an $\operatorname{Exp}(1/\theta)$ here. Am I doing something wrong?

A: Let $Y= \frac1X$

*

*$\mathbb P(X \ge x)= \exp(-\theta x)$ for $x >0$

*$\mathbb P(Y \le \frac1x)= \exp(-\theta x)$

*$\mathbb P(Y \le y)= \exp(-\theta / y)$ which is certainly not the CDF of an exponential distribution

The density for $Y$ is then $\frac{\theta}{y^2} \exp(-\theta / y)$ which, as tommik says, is called an inverse gamma distribution

A: You are right and your transformation is correct!
But without doing any calculation, what is true is that $X\sim \operatorname{Exp}(\theta)=\Gamma(1;\theta)$
And this means that $\frac{1}{X}\sim \text{Inv-Gamma}$
See "Related distributions" in this link

A: If $1/X \sim \operatorname{Exponential}(1/\theta)$ as claimed, then $\theta = 1$ would suggest $1/X$ is exponential with rate $1$ if $X$ is exponential with rate $1$.  This of course is absurd, since for example $$\Pr[X > 1] = e^{-1}$$ but $$\Pr[1/X > 1] = \Pr[X < 1] = 1 - e^{-1}.$$

A: Three things to note for finding CDF and PDF of functions of rvs:

*

*If the function is decreasing, the inequality sign flips

*It's often easier to find CDF first.

*Be careful if support of the function changes, e.g. if $Y= \log X$, you can only consider $X>0$ even if $X$ is defined on $X \leq 0$.
In your case, for $X>0$:
$$
F_Y(y) = P(Y \leq y) = P(\frac{1}{X} \leq y) = P(X \geq \frac{1}{y}) = \int_{\frac{1}{y}}^{\infty} \lambda e^{- \lambda x} dx = e^{-\frac{\lambda}{y}}
$$
Now use the definition of PDF (derivative of CDF):
$$
f_{Y}(y) = \frac{\lambda}{y^2}e^{-\frac{\lambda}{y}}, y > 0
$$


text:
Q: What is the proper name to call "non-developer bloggers"? I am looking for a proper name to address a group of people who is not proficient in coding a website (HTML/CSS/JS). A suitable call so not to offend anyone.
Example quotes (that I don't yet feel is correct):

"Useful codes for regular bloggers."
"Copy-paste solution for unskilled bloggers."
"Code snippets for non-technical developers."

Update:
A blogger is technically a website publisher too. Despite his coding skill / knowledge, one might prefer not to code and use available publishing tool as is.
After receiving some good suggestion on the topic, I think I should broaden the term
"non-developer" to something like bloggers who prefer not to code.
Do we have a suitable short name for that in English?

A: The option that comes to mind, focusing on what they actually do, is content creators.  This is a pretty common term these days.
Here are a few examples:

The 5 Habits of Highly Successful Content Creators
What Type Of Content Creator Are You? A Visual Guide To Your Copywriting Identity
The Unstoppable Rise of the Digital Content Creator

Another option would be blog authors -- that's what I was called back when I did that for a living.

A: Focus on labelling your content rather than who may be viewing it. Idioms such as "101" or "best practise" may be appropriate.

A: My suggestion:

non-developer bloggers

Or

non-coding bloggers

Or

"WYSIWYG" bloggers

WYSIWYG is an acronym that means "what you see is what is what you get" and is a common term for modern "make your own website" and various other editors.

A: Civilians. :-)
Newbie comes to mind.

An inexperienced newcomer to a particular activity.
  ODO.

"Copy-paste solution for newbie bloggers."
"Code snippets for newbie developers."


text:
Q: How to remove modal.js from all pages in magento 2.2 because of this file modal.js
define([
    'jquery',
    'underscore',
    'mage/template',
    'text!ui/template/modal/modal-popup.html',
    'text!ui/template/modal/modal-slide.html',
    'text!ui/template/modal/modal-custom.html',
    'Magento_Ui/js/lib/key-codes',
    'jquery/ui',
    'mage/translate'
], function ($, _, template, popupTpl, slideTpl, customTpl, keyCodes) {
    'use strict';
..

in website all pages these modal-popup content is being called but when you see its source code there is no modal.js exist.
please help me remove this.


text:
Q: Filling spinner in different thread Im trying to fill a spinner in my application in a different thread. Can somoene tell me why the following code is not working?
The following code is in the oncreate() method
Thread asyn = new Thread(){
       public void run(){
           try{
               int klok = 0;
               while(klok < 5000){
                   sleep(100);
                   klok = klok + 100;
               }

                try{

                   String[] items = new String[] {"One", "Two", "Three"};
                  ArrayAdapter<String> adapter = new ArrayAdapter<String>(Materiaal.this, android.R.layout.simple_spinner_item, items);
                  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                  spinner1.setAdapter(adapter);

                    }catch(Exception ex){
                       ex.printStackTrace();
                    }finally{
                        //adapter.notifyDataSetChanged();

                    }

           }catch(InterruptedException ex){
               ex.printStackTrace();
           }

       }
    };

    asyn.start();

A: I think you should use the method runOnUiThread(Runnable r) from the Activity.
Maybe do something like this
void run()
{
    // do stuff
    .
    .
    .
     activity.runOnUiThread(new Runnable()

         void run()
         {
             spinner1.setAdapter(adapter);
         }

     );
}

I hope it helps..

A: You must be getting View touched from wrong thread exception.
When you want to perform any UI operation from other than the main thread, you should use runOnUi(YOUR_RUNNABLE).

A: I'm pretty sure the error you're having is because you can't update the UI via other thread that isn't the UI thread.
To accomplish what you want, you should use AsyncTask (http://developer.android.com/resources/articles/painless-threading.html), do your work in the doInBackground() method and finally update your interface in the method onPostExecute().


text:
Q: ERROR AL IMPORTAR PAQUETES Cuando intento compilar la clase principal (CraftMania.java) desde la cmd me dice que no puede importar los paquetes del proyecto (no los encuentra): https://github.com/mcourteaux/CraftMania Se que tiene algo que ver con el classpath pero no se que hacer. Necesito ayuda porfavor.

A: Bienvenido al sitio!.
Como sugerencia, es mejor hacer esa tarea con la ayuda de algún IDE, es que por CMD uno tendría que referenciarle al classpath una por una las librerías necesarias de LWJGL (Lightweight Java Game Library) y Slick2D, creo son como 11 archivos jar.
Entonces...

*

*Con Eclipse, solo importas el proyecto 'CraftMania':

File > Import > General > Existing Project into Workspace

*

*Clic derecho en el nombre del proyecto y agregas las librerias
LWJGL y Slick2D:

Build Path > Configure Build Path... > Libraries > Add External JARs...

*

*Lo ultimo es también bastante importante, ese proyecto CraftMania tiene un directorio llamado natives; reemplaza su contenido con el de la carpeta native que se descargó con lwjgl-2.9.3 con el fin de evitar un detestable error java.lang.LinkageError (dado porque la version de las librerias 2.9.3 es distinta de la que usaron para compilar este proyecto anteriormente).

Espero haber sido lo mas preciso y descriptivo posible.


text:
Q: visual studio 2010: how to auto replace concrete types with interface I read the book How to work with legacy code
It said that in many IDEs there is an option to automatically

*

*extract an interface from a class

*replace classes members from concrete to the new interface
I have found the first option in VS2010, does anyone know how to do the second?

A: Think out of the box.
First rename your class

*

*MyClass to IMyClass and tell VS to rename references

*rename it back to MyClass and don't rename references

*extract interface to IMyClass

A: use Resharper a visual studio add on. It costs but you can get a free trial for 30days I think. Its very good and can do what you mentioned.


text:
Q: Using a shared_ptr from a stored shared_ptr I have some data stored using an std::shared_ptr<T>.
Now I want to use that that as const input to a function, so I need an std::shared_ptr<const T>. How do I do that?
Can I pass the std::shared_ptr<T> object to the function expecting a std::shared_ptr<const T>?

A: Yes.
#include <memory>

void foo(std::shared_ptr<const int> ptr) {}

int main()
{
    auto ptr = std::make_shared<int>();
    foo(ptr);
}

Why didn't you just try it?