Q: Replacing Pseudo-SRAM with SRAM This week I am repairing an old Game Gear, suffering from bad video memory. The original IC is a HM65256BLFP-10T: an asynchronous Pseudo-Static 8-bit 32k-word RAM with an access time of 100ns.
I would like to replace it with a similar memory, but I do not understand some of the terminology regarding this type of ICs. Does it matter if my new RAM is rated as a CMOS Static RAM? Can I replace a PseudoSRAM with an SRAM?. Is there any risk (damaging other components or modifying the game experience in any way) on choosing a memory with more capacity or less access time?
I have been reading he datasheets of some ICs. Would either Hitachi HM62256BLFP or Sony CXK58257AM do the job? I accept suggestions

A: I'll expand on my comment.
A bit of background
Pseudo SRAM is actually a dynamic RAM (DRAM) made to mimic a regular static RAM. Dynamic RAM allows packing much more bits in the same silicon area, so allows for bigger memory sizes (or cheaper price for the same size). The problem is, interfacing with DRAM is a bit more complicated, and, even more annoying, it requires regular refresh of its contents, or you loose it over time. Manufacturers therefore made what is known as Pseudo Static RAM, a DRAM array that has a builtin circuitry automatically refreshing the contents at the appropriate times, and having an additional layer of logic to make the interface look like a regular SRAM.
Differences in operation
There are a bit more constraints when using pseduo SRAM, though. Because the refreshing takes place internally, the reading/writing operations must not be made too slowly, so that internal refreshing cycles can be made in time. See your original chip datasheet: the chip enable pulse width must not exceed 4ms. This constraint doesn't exist in a regular SRAM, you can leave the chip enable active for as long as you want. This difference shouldn't be a problem in your case (it could have if you were doing the opposite: replacing a regular SRAM by a pseudo SRAM).
Now, there is something I must say don't quite understand in the specific case of the original HM65256B chip you have: there are two special operations that are documented in the datasheet: "automatic refresh cycle" and "self refresh cycle". Honestly, I can't really tell why they are here (the datasheet is a bit laconic), since the supposed purpose of a pseudo SRAM should be to hide the details of the refreshing requirements. If you look at the datasheets of today's pseduo SRAMs, you won't see these (there is an internal on-chip timer to trigger the refreshing in time). Maybe the older pseudo SRAM still required the refresh to be triggered externally, I don't know. Anyway, looking at the chronograms for these special cycles, I can say they wouldn't have any effect on a regular SRAM, so it is not a problem either.
There is also one specific data access method I have seen in your original pseudo SRAM datasheet: the "static column mode cycle". Basically, if you change only the A8-A14 lines of the address and keep the same A0-A7, you can access data in a faster time (because you don't change row). In your case, it is 55ns. If the CPU takes advantage of this access mode, then you need to be careful here. Choose a replacement SRAM that has a 55ns access time to avoid problems.
Physical interface
The pinout is the same. So this isn't a problem.
Also, supply voltage, and the input and output voltage levels specified are similar between the original chip and the two replacement chips you suggest. So this is fine too.
Other concerns
The fact the replacement RAMs are qualified as "CMOS" isn't a problem. Your original RAM's datasheet didn't mention CMOS because DRAM is another manufacturing process, but whatever.
Is there a risk of damaging other components? I think the main risk of damage is when you'll desolder/solder the parts. But if the mechanical part goes well, I see close to zero risk that changing the old RAM by the one you suggest will damage anything. In the worst case, it just won't work (for some reason I can't foresee). It could damage something eventually if the contents of the memory read back by the CPU was corrupted, and would indirectly lead the CPU to do crazy stuff with other peripherals somewhere. But this is very unlikely (actually, almost impossible since you said it was video memory).
Choosing a chip with lower access time? No problem. The limit is 55ns, as I explained above. Anything below is fine.
Choosing a chip with more capacity? In theory, it is not a problem either, provided that you maintain the additional address line to a constant logic low (or logic high). However, the problem is that for bigger chips, the pinout is different, so in practice, it is going to be difficult.
Will it change the game experience? No. Games won't go faster if the memory is faster. The speed is decided by the CPU and the crystal.
Conclusion
It you're confident on your soldering skills, and if you choose one of your replacement chip with 55ns (or lower) access time, it is totally worth a try.


Q: Set branch permissions from Azure DevOps Pipeline with tf.exe I have a Powershell script that tries to set branch permissions that is getting called in a Build Pipeline. Unfortunately, I am getting an unauthorized error and I'm not sure why.
Code Snippet:
$tfExe = "$(split-path -parent $MyInvocation.MyCommand.Definition)\tf.exe"
& $tfExe git permission /deny:CreateBranch /group:[$project]\Contributors /collection:https://dev.azure.com/$organization/ /teamproject:$project /repository:$reposiName /login:$username,$pat
& $tfExe git permission /allow:CreateBranch /group:[$project]\Contributors /collection:https://dev.azure.com/$organization/ /teamproject:$project /repository:$reposiName /branch:feature /login:$username,$pat

Error Message:

TF30063: You are not authorized to access
  https://dev.azure.com/Company-DevOps. TF30063: You are not authorized
  to access https://dev.azure.com/Company-DevOps. TF30063: You are not
  authorized to access https://dev.azure.com/Company-DevOps.

Powershell Script in Build Pipeline:

Any thoughts?

A: The username & password in the /login is for Azure DevOps Server. for Azure DevOps you should use OAuth:
param ($oauth)
/loginType:OAuth /login:.,$auth

In the agent job options you need to enable the "Allow scripts to access the OAuth token":

And pass the $(System.AccessToken) as oauth parameter:

A: So I wasn't able to get this to work with tf.exe as Microsoft Docs advised us to, but I was able to figure it out with the help of a blog here.
Step 1
Get the $descriptor value for the Contributors group
$descriptor = az devops security group list --org https://dev.azure.com/$organization --project $project | ConvertFrom-Json | select -expand graphGroups | where principalName -eq "[$project]\Contributors"

Step 2
Create your token values for the branches you want. Unfortunately, you cannot explicitly state which branch pattern you would like. Azure DevOps requires the Hex value (don't ask)
#Create the tokens
function hexify($string) {
    return ($string | Format-Hex -Encoding Unicode | Select-Object -Expand Bytes | ForEach-Object { '{0:x2}' -f $_ }) -join ''
}

$hexFeatureBranch = hexify -string  "feature"
$featureToken = "refs/heads/$hexFeatureBranch"

$hexSprintBranch = hexify -string  "sprint"
$sprintToken = "refs/heads/$hexSprintBranch"

$hexHotfixBranch = hexify -string  "hotfix"
$hotfixToken = "refs/heads/$hexHotfixBranch"

Step 3
Get the Namespace ID for your Git Repos
#Get the namespace ID for the organization's Git repos
$namespaceId = az devops security permission namespace list --org "https://dev.azure.com/$organization/" --query "[?@.name == 'Git Repositories'].namespaceId | [0]"

Step 4
Get the project's JSON object from the server
#Get the Project's JSON object
$projectObj = az devops project show --org https://dev.azure.com/$organization --project $project | ConvertFrom-Json
$projectid = $projectObj.id

Step 5
Put a Deny on CreateBranch for every branch in your repo. The Azure CLI requires you to know which bits for allow and deny need to be. Luckily, I was able to do this by capturing the JSON response when I did it via the UI.
$denyBranch = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token "repoV2/" --deny-bit 16 --allow-bit 16494

Step 6
Put an Allow on CreateBranch for every branch that has the pattern feature/, sprint/ and hotfix/*
$featureTokenBuild = "repoV2/$projectid/$repoid/$featureToken"
$sprintTokenBuild = "repoV2/$projectid/$repoid/$sprintToken"
$hotfixTokenBuild = "repoV2/$projectid/$repoid/$hotfixToken"

$allowCreateBranchFeature = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token $featureTokenBuild --deny-bit 0 --allow-bit 16
$allowCreateBranchSprint = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token $sprintTokenBuild --deny-bit 0 --allow-bit 16
$allowCreateBranchHotfix = az devops security permission update --id $namespaceId --org https://dev.azure.com/$organization --subject $descriptor.descriptor --token $hotfixTokenBuild --deny-bit 0 --allow-bit 16

It wasn't easy but at least for anyone in the future looking to do the same, here is the solution!


Q: Blocked by Play Protect for a signed release APK I have a React Native (Android) app and for which I signed as per the instructions here;
https://reactnative.dev/docs/signed-apk-android
I generated a release APK which is also all fine (no errors).  I then downloaded the APK to my android device and when I clicked to install I got a message to say the below.

This app is not to be published to the Play Store but we will supply a URL to our customers to download the APK.  So I want users to be able to install the APK without getting this warning.
What I found so far

*

*Disabling the play protect on the device (We don't want our customers to do this)

*Publishing to the play store (We will supply a URL to download the APK)

*Play Protect Appeals Submission Form (Is this only for apps to be published to the play store? If not, how does it work once it is verified?)

Thanks all.

A: Play Protect Appeals Submission Form can solve your problem. Just send your apk details to Google and wait for appeal process. When you enter your apk's URL, Google will control your apk. Just enter your URL to URL to download your APK file section. You do not need publish your app.


Q: Ember inject function I have some function which i use in couple controllers
 App.AController=Ember.Controller.Extend({
    area:function(){}
});
App.BController=Ember.Controller.Extend({
    area:function(){}
});

cause i new in Ember i want something to write function in one place and then inject function in Controllers. I try something with services but doesn't work i got error that Ember.Service is not defined, so if someone can write example!
I use ember 1.10.

A: If you use ember-cli just create a file app/utils/area.js:
export default function () {...};

and then you can import it and use it:
import area from 'myapp/utils/area`;
import Ember from 'ember';

export default Ember.Controller.extend({
  area,
});

However if you'r not using ember-cli, this question is not ember specific. Then it depends how you organize your code. But you really should check out ember-cli!
But always remember, this is just javascript. This is valid code:
function area() {
    ...
}

App.AController=Ember.Controller.Extend({
    area
});
App.BController=Ember.Controller.Extend({
    area
});


Q: How to get JaCoCo instrumentation code coverage while executing webApplication on server I want to get a code coverage report (or tracking controller flow of an application) when I execute the some scenario on live application i.e. while application running in server, so I have refereed the official Jacoco documentation  and did as fallows
As a first step, I tried to bind the jacoco agent to the application running port
export MAVEN_OPTS=-javaagent:/home/user/.m2/repository/org/jacoco/org.jacoco.agent/0.7.4.201502262128/org.jacoco.agent-0.7.4.201502262128-runtime.jar=includes=*,output=tcpserver,port=6300,address=*,dumponexit=true

then I have started the server and executed some test scenarios by that time I have also requested jacoco to get the dump by executing following command
 mvn jacoco:dump

when I executed the above command first it showed like java.net.BindException: Address already in use then it printed as fallows
[INFO] Connecting to localhost/127.0.0.1:6300

When I stopped the server jacoco.exec has been generated to a known location there after I have requested to generate a jacoco report by executing the following command
mvn jacoco:report

Finally I got the report but when I open the index.html page it showed 0% coverage.
you can reproduce my difficulty with following sample Spring MVC project
please download Spring MVC project from https://github.com/mkyong/spring4-mvc-ajax-example from the Github
In my case I am using WildFly 8.x server to run the project and add the following dependencies to downloaded projects pom.xml
 maven-surefire-plugin of 2.19.1 version
 jacoco-maven-plugin of 0.7.4.201502262128 version
 junit of 4.12 version

Then clean and build the project by using following commands.
mvn clean install

once it is done get the .war file from target folder of the project and keep inside the wildfly serverwildfly-9.0.0.CR2/standalone/deployments/ folder
Once the .war is deployed go to /wildfly-9.0.0.CR2/bin/ folder and execute/run the ./standalone.sh file or depending on platform you can run the.dat/.sh file
once project is deployed and server is started execute the following command
mvn jacoco:dump

it displayed like listening/connected to localhost/127.0.0.1:6300
Then execute some test scenarios and execute following maven command
mvn jaococ:report

Finally report will be generated with 0% coverage!.
Downloaded project can be found in  MKyong website
Please help me to get the code coverage report and any help will be appreciated.

A: JaCoCo requires the exact same class files for report generation that were used at execution time, so

*

*if report is completely empty, then classes were not provided

*if report contains classes but their coverage is 0%, then they don't match classes that were used at runtime - this is described along with other related information in JaCoCo documentation on page http://www.jacoco.org/jacoco/trunk/doc/classids.html
and in either case check existence of warnings in log.
Update for updated question
Here is what I did:

*

*downloaded and unpacked JaCoCo 0.7.9 into /tmp/jacoco/jacoco-0.7.9

*downloaded and unpacked Wildfly 9.0.0.CR2 into /tmp/jacoco/wildfly-9.0.0.CR2

*cloned https://github.com/mkyong/spring4-mvc-ajax-example into /tmp/jacoco/spring4-mvc-ajax-example and built as mvn verify

*copied /tmp/jacoco/spring4-mvc-ajax-example/spring4-mvc-maven-ajax-example-1.0-SNAPSHOT.war into /tmp/jacoco/wildfly-9.0.0.CR2/standalone/deployments

*Wildfly started as JAVA_OPTS=-javaagent:/tmp/jacoco/jacoco-0.7.9/lib/jacocoagent.jar=output=tcpserver ./standalone.sh and got enough time to deploy application

*in directory /tmp/jacoco/spring4-mvc-ajax-example executed mvn org.jacoco:jacoco-maven-plugin:0.7.9:dump org.jacoco:jacoco-maven-plugin:0.7.9:report (note that version of used agent matches version of jacoco-maven-plugin) so that it created /tmp/jacoco/spring4-mvc-ajax-example/jacoco.exec and report /tmp/jacoco/spring4-mvc-ajax-example/site/jacoco:

*opened http://localhost:8080/spring4-mvc-maven-ajax-example-1.0-SNAPSHOT/ and did some actions

*executed mvn org.jacoco:jacoco-maven-plugin:0.7.9:dump org.jacoco:jacoco-maven-plugin:0.7.9:report again to get an updated report:


Q: How to add exclude data in Firebase rules on multiple levels? I have my rules set. Normally, all data can only be read by the person who is auth to do so. However, I want to make exceptions. These are my rules:
 "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid",
        "ForEveryone": {
        ".read": true,
          ".write": true
        }
        "NoWrite" : {
          ".read": true,
          ".write": false
        }
      }
    }

So I let's say I have 3 string. String 1 is called private and can the auth person can read and write. String 2 is ForEveryone, so everyone can change and write data. String 3 is NoWrite, for everyone but you can not write to it.
I get an error, saying:Expecting a ; or " at the line NoWrite. So what am I doing wrong? Is it a wrong placed }? Thank you.

A: The approach you're taking to your rule structure won't work. Firebase security rules cascade, meaning that a permission given to any node will apply to any of its children and on down the tree. You cannot grant read or write access on a node and then revoke it further down. (But you can grant permissions not granted above.) See the docs on rule cascading.
In your case, you want to have some user data that be can written to by anyone and some that cannot. It's not clear from your example whether you want NoWrite to be written only by the authenticated user, or by nobody. Depending on how you will be reading this data, you will need to either separate these data into different collections, or make $uid inaccessible and define your rules only for ForEveryone and NoWrite.
The first approach might look like this:
 "rules": {
    "users-public": {
      "$uid": {
        ".read": "true",
        ".write": "true",
      },
    "users-nowrite": {
      "$uid": {
        ".read": "true",
        ".write": "$uid === auth.uid"
      }
    }

Or the second, like this:
 "rules": {
    "users": {
      "$uid": {
        "ForEveryone": {
          ".read": "true",
          ".write": "true"
        },
        "NoWrite" : {
          ".read": "true",
          ".write": "$uid === auth.uid"
        }
      }
    }

As to your syntax error, you need a comma , after the closing brace before "NoWrite".

A: Here are your rules, properly spaced so you can see the relationship between the parent nodes and child nodes. It seems this is not what you want. So this isn't really an answer but will lead to a better question that we can answer. Will update once we know what the OP is after.
{
    "rules": {
        "users": {
           "$uid": {
               ".read": "$uid === auth.uid",
               ".write": "$uid === auth.uid",
               "ForEveryone": {
                   ".read": true,
                   ".write": true
               },
               "NoWrite" : {
                   ".read": true,
                   ".write": false
               }
           } //end uid
         } //end users
     } //end rules
} //outside closure


Q: Why the first if statement conditional is ignored and the last else is executed? When I type in John and 0 the "John is great" statement is not executed. I don't understand why.
I know that the question might be really simple but I checked the code in Java and it was working correctly.
print("Hello world")
myName = input("What is your name?\n")
myVar = input("Enter a number: ")

if(myName == "John" and myVar == 0):
    print("John is great")
elif(myName == "Bob"):
    print("You are ok")
else:
    print("Hello world")

A: myVar is str type. Not int type.
You should fix myVar = int(input("Enter a number: "))

A: 0 and "0" are two different values. 0 == 0 is true; 0 == "0" is false.
input always returns a str, so entering 0 sets myVar to "0", not 0.
if myName == "John" and myVar == "0":


Q: undefined attribute in use of $controllerProvider in Angular I'm a newbie in Angular, i whant to make use of $controllerProvider, i see an example like my code, but the attribute register got undefined:
var appTmw = angular.module('appTmw', ['ui.router']);

appTmw.config(function($stateProvider, $urlRouterProvider, $controllerProvider) {

    appTmw.register = {
        controller: $controllerProvider.register
    };
})

and here, a register of controller, the register attribute got undefined:
appTmw.register.controller('CustomersController', ['$scope', 'config', 'dataService',
   function ($scope, config, dataService) {

      //Controller code goes here
   }]);

what a problem with the code?

A: controllerProvider is the $controller service used by Angular to create new controllers:
https://docs.angularjs.org/api/ng/provider/$controllerProvider
If you are new to angular I suggest you to use the standard way to create a controller:
var appTmw = angular.module('appTmw', ['ui.router']);

appTmw.controller('controllerName', function($scope){

//your code for the controller here

});

I hope it helps.


Q: Catch if user presses enter key in textbox I'm trying to catch in a Event if the user presses the enter key. If followed these instructions found on the MSDN documentation pages.
This is my Event code for the Textbox:
Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub

My problem is: when I push any button on the keyboard the Event is triggered, but when I press the enter ( return ) key nothing happens?
I tried changing the Textbox property to AcceptsReturn = True but no luck.
Extra info: The textbox is located on a UserControl and not a form control.

A: If something else is stopping the text box from receiving the enter key you could try overriding ProcessCmdKey of the UserControl instead.
It might work, but it all depends on where in the event chain that the parent intercepts the message.
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
    If keyData = Keys.Return AndAlso tbOccurrenceElevation.Focused = True Then
        'Do your stuff here.
        Return True 'We've handled the key press.
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

A: Try this:
Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Enter or e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub

You have to remember most of the keyboards have both Enter and Return. The code for those is different so you have to include them both


Q: Adding Icons on TabBottomNavigation React Native I have This navigation, how can I add Icons on the bottomTabNavigator
const switchNavigator = createSwitchNavigator({
      mainFlow: createBottomTabNavigator({
        Home: createStackNavigator({
          Search: SearchScreen,
          Results: ResultsShowScreen
        }),
        Map: AccountScreen,
        Scanner: AccountScreen,
        Account: AccountScreen
      })
    });

A: U can add icons to tabs using defaultNavigationOptions, here is an example,
more information about tabs can be got from https://reactnavigation.org/docs/en/4.x/tab-based-navigation.html
export default createBottomTabNavigator(
  {
    Home: HomeScreen,
    Settings: SettingsScreen,
  },
  {
    defaultNavigationOptions: ({ navigation }) => ({
      tabBarIcon: ({ focused, horizontal, tintColor }) => {
        const { routeName } = navigation.state;
        let IconComponent = Ionicons;
        let iconName;
        if (routeName === 'Home') {
          iconName = focused
            ? 'ios-information-circle'
            : 'ios-information-circle-outline';
          // Sometimes we want to add badges to some icons.
          // You can check the implementation below.
          IconComponent = HomeIconWithBadge;
        } else if (routeName === 'Settings') {
          iconName = focused ? 'ios-list-box' : 'ios-list';
        }

        // You can return any component that you like here!
        return <IconComponent name={iconName} size={25} color={tintColor} />;
      },
    }),
    tabBarOptions: {
      activeTintColor: 'tomato',
      inactiveTintColor: 'gray',
    },
  }
);```


Q: Why do browsers have 3 characters as protocol separator? http:// vs http:
Either there is some historical reason or I'm missing something.

A: According to RFC 1738,

While the syntax for the rest of the URL may vary depending on the
particular scheme selected, URL schemes that involve the direct use
of an IP-based protocol to a specified host on the Internet use a
common syntax for the scheme-specific data:
//user:password@host:port/url-path
Some or all of the parts "user:password@", ":password",
":port", and "/url-path" may be excluded.  The scheme specific
data start with a double slash "//" to indicate that it complies with
the common Internet scheme syntax.

A: //                Indicates that a contact to a server is to be achieved. (For example, when sending email the notation 'mailto:<email address>...', without slashes, could be used). Note that this doesn't mean a connection between a browser and server. When a browser has sent a request, there is no connection between the browser and the server.


Q: Appropriate usage of the word "adverse" I have a problem with using the word "adverse". Is this sentence correct?

My father was adverse me to become a teacher

A:
I have a problem with using the word "adverse".

A person cannot be adverse.  The typical phrase with adverse is "adverse effect" meaning an effect that prevents success.
As @Mick and others in the comments say, averse is likely what you mean, and a person can definitely be averse to things.
You can't put an object pronoun right after {to be} + {adjective}, it looks like you are trying to use {adjective} as a transitive verb and it doesn't make sense.  In this case it almost looks like you're trying to say advise which is transitive but means something different entirely.


Q: Browsersync - How to choose which installation of browser to run? I've just installed Firefox Dev Edition, and I don't know how to tell browsersync to start with it when I launch it.
I know there is the browser option in which I can specify "firefox", but how can I differenciate one FF installation from one other ?
The issue would be the same if I had various regular FF installed (eg a 3.5, a 48.x and a 50.x).
I can always open manually the right FF and load the page after browsersync started, but I would like it to do it manually (and not to be opened in my regular non-dev FF).

A: In fact, it was quite easy: if you put the absolute path to an executable file in the browser option, it takes it smoothly.
So options should be something like :
{ port: 9000,
    server: {
      baseDir: [...
      ],
      routes: {
        '/bower_components': 'bower_components',
        '/node_modules': 'node_modules',
        '/temp': 'temp'
      }
    },
    logLevel: 'info',
    notify: true,
    browser: 'C:\\Program Files (x86)\\Firefox Developer Edition\\firefox.exe',
    reloadDelay: 0 //1000
}


Q: Best way to inform user of an SQL Table Update? I have a desktop python application whose data backend is a MySQL database, but whose previous database was a network-accessed xml file(s). When it was xml-powered, I had a thread spawned at the launch of the application that would simply check the xml file for changes and whenever the date modified changed (due to any user updating it), the app would refresh itself so multiple users could use and see the changes of the app as they went about their business.
Now that the program has matured and is venturing toward an online presence so it can be used anywhere. Xml is out the window and I'm using MySQL with SQLAlchemy as the database access method. The plot thickens, however, because the information is no longer stored in one xml file but rather it is split into multiple tables in the SQL database. This complicates the idea of some sort of 'last modified' table value or structure. Thus the question, how do you inform the users that the data has changed and the app needs to refresh? Here are some of my thoughts:

*

*Each table needs a last-modified column (this seems like the worst option ever)

*A separate table that holds some last modified column?

*Some sort of push notification through a server?

*It should be mentioned that I have the capability of running perhaps a very small python script on the same server hosting the SQL db that perhaps the app could connect to and (through sockets?) it could pass information to and from all connected clients?

Some extra information:

*

*The information passed back and forth would be pretty low-bandwidth. Mostly text with the potential of some images (rarely over 50k).

*Number of clients at present is very small, in the tens. But the project could be picked up by some bigger companies with client numbers possibly getting into the hundreds. Even still the bandwidth shouldn't be a problem for the foreseeable future.

Anyway, somewhat new territory for me, so what would you do? Thanks in advance!

A: As I understand this is not a client-server application, but rather an application that has a common remote storage.
One idea would be to change to web services (this would solve most of your problems on the long run).
Another idea (if you don't want to switch to web) is to refresh periodically the data in your interface by using a timer.
Another way (and more complicated) would be to have a server that receives all the updates, stores them in the database and then pushes the changes to the other connected clients.
The first 2 ideas you mentioned will have maintenance, scalability and design uglyness issues.
The last 2 are a lot better in my opinion, but I still stick to web services as being the best.


Q: Double loop in Ansible, how to deal with it? I have this construction:
- name: Run validation query on db localy
  shell: >
    docker exec postgres.1.$(docker service ps -f "name=postgres.1" postgres -q) bash -c 'psql -v --username "{{ pg_connection_speruser }}" --dbname "{{ pg_db }}" -c "select 1"'
  register: validation_query
  delegate_to: "{{ item }}"
  with_items: "{{ groups.postgres_server }}"
  until: validation_query.stderr == ''
  retries: 6
  delay: 10
  ignore_errors: false
  changed_when: false

What i need is to do:
- name: Run validation query on db localy
  shell: >
    docker exec postgres.{{ item }}.$(docker service ps -f "name=postgres.{{ item }}" postgres -q) bash -c 'psql -v --username "{{ pg_connection_speruser }}" --dbname "{{ pg_db }}" -c "select 1"'
  register: validation_query
  with_sequence: start=1 end="{{ pg_docker_service_replicas }}"
  delegate_to: "{{ item }}"
  with_items: "{{ groups.postgres_server }}"
  until: validation_query.stderr == ''
  retries: 6
  delay: 10
  ignore_errors: false
  changed_when: false

But of course, there is a problem with double loop with_sequence and with_items.
Is possible to do it in another way? Thanks

A: You can do this with with_nested and lookup:
---
- hosts: localhost
  gather_facts: no
  vars:
    max_num: 3
    delegates:
      - host1
      - host2
  tasks:
    - debug:
        msg: "delegate={{ item[0] }} seq={{ item [1] }}"
      with_nested:
        - "{{ delegates }}"
        - "{{ lookup('sequence','start=1 end='+max_num|string,wantlist=True) }}"

This will generate nested loop: outer one – over each item in delegates list (accessible via item[0]), inner one – over sequence 1-max_num.


Q: Is it possible for WebDriver to click an element with a mouseclick event that invokes a JavaScript file that includes a test tracker? This is a question I have that arises from another user's question. If you look at my answer there, you will get some context for this question. The URL for the web page I am going to is https://hotels.ctrip.com/hotel/347422.html?isFull=F#ctm_ref=hod_sr_lst_dl_n_1_8 if you want to check it out for yourself.
Consider the python selenium script found at the bottom of the question.  Nothing happens when selenium tries to click on this element:
browser.find_element_by_xpath('//*[@id="cPageBtn"]').click()
Same thing with this element
browser.find_element_by_xpath('//*[@id="appd_wrap_close"]').click()

When debugging my selenium script for each element, I confirmed that selenium can find the element just fine;  it is not hidden, inside an iFrame, disabled, or any other oddity that I normally check for failed selenium actions.
However, it has a mouseclick event that invokes an interesting JavaScript file, and I was actually able to access it by navigating to URL shown here:

Hovering over the URL revealed that it is https://webresource.c-ctrip.com/ResUnionOnline/R3/float/floating_normal.min.js?20190306:2.
At the very beginning of the file I found
document.getElementById("ab_testing_tracker") && "abTestValue_Value" != h ?
document.getElementById("ab_testing_tracker").value

So I search (via CSS selector in the dev console) the webpage HTML for an element with an id of "ab_testing_tracker" and I am less than surprised that it returns nothing.  Then I unminified and searched through the file for all instances of "ab_testing_tracker".  That led me to this element:
document.getElementsByTagName("body")[0].insertAdjacentHTML("afterBegin","<input type='hidden' name='ab_testing_tracker' id='ab_testing_tracker' value='"+h.split("|")[1]+"'>")
Well, it appears there is a hidden input node inserted in the body of the document for the purpose of automation tracking.  Google searching revealed that automation tracking is often accomplished by looking at the navigator.userAgent property and finding userAgents that indicate automation.  But the script is using a random legitimate userAgent every time, so I don't think the userAgent is how the detection is finding selenium.
Summary and possible workarounds
Selenium can't click certain elements on the web page likely due to testing tracking by the website. There are a couple things I thought of to get around
it: maybe I can disable click events when using selenium? This I don't know how to do and couldn't find a way after searching online. Next, I tried to click on it with a Javascript executor, but that didn't work.
Does anyone know a way to get around the test tracker and click the desired element?
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By

# url
url = "https://hotels.ctrip.com/hotel/347422.html?isFull=F#ctm_ref=hod_sr_lst_dl_n_1_8"

# User Agent
User_Agent_List = ["Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2",
                   "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
                   "Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)",
                   "Opera/9.80 (X11; Linux i686; U; ru) Presto/2.8.131 Version/11.11",
                   "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2",
                   "Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1",
                   "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25"]

# Define the related lists
Score = []
Travel_Types = []
Room_Types = []
Travel_Dates = []
Comments = []

DEFINE_PAGE = 10

def next_page():

    current_page = int(browser.find_element_by_css_selector('a.current').text)

    # First, clear the input box
    browser.find_element_by_id("cPageNum").clear()
    print('Clear the input page')

    # Second, input the next page
    nextPage = current_page + 1
    print('Next page ',nextPage)
    browser.find_element_by_id("cPageNum").send_keys(nextPage)

    # Third, press the goto button
    browser.find_element_by_xpath('//*[@id="cPageBtn"]').click()

def scrape_comments():
    """
    It is a function to scrape User comments, Score, Room types, Dates.
    """
    html = browser.page_source
    soup = BeautifulSoup(html, "lxml")
    scores_total = soup.find_all('span', attrs={"class":"n"})
    # We only want [0], [2], [4], ...
    travel_types = soup.find_all('span', attrs={"class":"type"})
    room_types = soup.find_all('a', attrs={"class":"room J_baseroom_link room_link"})
    travel_dates = soup.find_all('span', attrs={"class":"date"})
    comments = soup.find_all('div', attrs={"class":"J_commentDetail"})
    # Save score in the Score list
    for i in range(2,len(scores_total),2):
        Score.append(scores_total[i].string)
    Travel_Types.append(item.text for item in travel_types)
    Room_Types.append(item.text for item in room_types)
    Travel_Dates.append(item.text for item in travel_dates)
    Comments.append(item.text.replace('\n','') for item in comments)

if __name__ == '__main__':

    # Random choose a user-agent
    user_agent = random.choice(User_Agent_List)
    print('User-Agent: ', user_agent)

    # Browser options setting
    options = Options()
    options.add_argument(user_agent)
    options.add_argument("disable-infobars")

    # Open a Firefox browser
    browser = webdriver.Firefox(options=options)
    browser.get(url)

    browser.find_element_by_xpath('//*[@id="appd_wrap_close"]').click()

    page = 1
    while page <= DEFINE_PAGE:
        scrape_comments()
        next_page()

    browser.close()

A: The problem is not the tracking or the click event, the problem is timing and possibly browser size.
Maximize the browser window and add explicit wait when searching for the banner close button
browser = webdriver.Firefox(options=options)
browser.maximize_window()
browser.get(url)

wait = WebDriverWait(browser, 10)

wait.until(EC.element_to_be_clickable((By.ID, 'appd_wrap_close'))).click()
wait.until(EC.invisibility_of_element_located((By.ID, 'appd_wrap_default')))

current_page = int(browser.find_element_by_css_selector('a.current').text)
next_page = current_page + 1

page_number_field = wait.until(EC.visibility_of_element_located((By.ID, 'cPageNum')))
page_number_field.clear()
page_number_field.send_keys(next_page)
wait.until(EC.element_to_be_clickable((By.ID, 'cPageBtn'))).click()


Q: %0d%0a getting added behind the URL of a href attribute in an  tag In a helper plugin for WooCommerce for WordPress, I'm trying to create a custom message to be sent to a buyer.
I don't know why in all the emails that are sent out, %0d%0a is getting added behind the URL in the href attribute. I have tried several different combinations and nothing is working.
This is what I'm trying to do:
echo " Please click here to redeem the coupon";
But because %0d%0a is being added at the back of it the URL doesn't work properly for coupon codes.
This is what the URL looks like afterwards:
https://www.example.com/product-1/?couponCode=TDXGUA9G&utm_source=test&utm_medium=testt&utm_campaign=test&aff_code=TSJU89XYZ%0d%0a
The only thing that doesn't add %0d%0a is this:
 echo $cl;

But I want to be able to use the  tag so that the buyer doesn't have to click on a long URL link.

A: Try this
echo " Please click here to redeem the coupon";

If you still have the issue, check how $cl was created.

A: I really appreciate all the responses. But I just want to post the code that finally worked for me after 7 hours of work. I understand that it looks silly but this is the best I could do for now. Here's what worked for me:
    ?>
    <a href='<?php echo trim($cl); ?>'> Click here to take <?php echo ' '.$_product_name.'';

A: I just encountered the same issue, but I'm using ASP.NET. All I did was delete the single quote and type it again. Now it works.
<asp:HyperLink ... NavigateUrl='<%# Eval("Url") %>' Text='<%# Eval("Name") %>' />

There were possibly some extra invisible characters which needed to be deleted.


Q: Does changing wire gauge change output of a thermocouple? So I've been experimenting creating thermocouples with copper and constantan wire, just by twisting them together at one end and heating the junction with a candle and using a voltmeter to measure the emf at the other end. I thought that changing the gauge of the copper wire might change the emf output, and it appears that the smaller the diameter of the wire the larger the voltage is, but I'm not sure why this is. From research, it looks like the thermoelectric efficiency is determined by the Seebeck coefficient, the thermal conductivity, and the electrical conductivity, as well as the temperature difference.
Since the conductivities are intrinsic properties of the copper and I'm keeping the temperature constant, I'm not sure why the output of the thermocouple is changing. I thought that I might be changing the conductivity in some way by changing the gauge, but is this possible?

A: Thicker wires mean you are heating the 'cold' end more (and, as in the comment) drawing more heat from the hot end. To a rough approximation the no-load voltage is proportional to the temperature difference between the ends.
A long thick wire (long enough the cold end does not heat appreciably) should not be any different from a long thin wire pair if the alloys are similar and negligible current is drawn.
Think of a heat engine, if that makes sense, when you start drawing current the resistance figures into it as well as the heat flow down the wires.
To get a good reading you have to have both ends at controlled temperatures. For a rough measurement (maybe within 2-3 degrees C) you can put one end (the junction) in boiling water and the other (transition junction(s) to copper on both sides) into an ice-water slurry.

A: You may be having types of difficulty.

*

*The voltage may be affected by the quality of the junction. Twisting the wires together is not going to make a good thermocouple junction. They should be welded together at a single point.

*When you connect the voltmeter to the thermocouple wires, you create two more thermocouples. There are various ways to compensate for that. One is to make two thermocouples with the thermocouple wire. Connect two copper wires to opposite ends of the constantan wire. Measure the voltage at the ends of the copper wires. Has one of the copper-constantan junctions leave the other at room temperature or put it in ice water. The voltage should be proportional to the temperature difference between the two junctions.


Q: Options ExecCGI is off in this directory: /home/ec2-user/public_html/cgi-bin/ When I tried to access the http://host-ip/~ec2-user/cgi-bin/try.cgi, I got 403 Forbidden error, error_log shows Options ExecCGI is off in this directory: /home/ec2-user/public_html/cgi-bin/try.cgi. If I commented out AddHandler line, I can see the script text, though. Below is some basic information. Do you have any clue what is preventing the server from parsing CGI scripts? Thanks!
[ec2-user@ip-10-245-79-145 cgi-bin]$ uname -a
Linux ip-10-245-79-145 3.4.37-40.44.amzn1.x86_64 #1 SMP Thu Mar 21 01:17:08 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

[ec2-user@ip-10-245-79-145 cgi-bin]$ apachectl -v
Server version: Apache/2.2.24 (Unix)
Server built:   Apr 30 2013 22:53:39

[ec2-user@ip-10-245-79-145 cgi-bin]$ tail /etc/httpd/conf/httpd.conf
<Directory "/home/ec2-user/public_html/cgi-bin/">
        Options +ExecCGI
        AddHandler cgi-script .cgi
        Order allow,deny
        Allow from all
</Directory>

No .htaccess file in the /home/ec2-user/public_html/cgi-bin/ directory, no SELinux running, suexec.log shows nothing.

A: Finally I figured out the reason after reading how sections are merged, my script works after commenting out the following lines in my httpd.conf:
<Location />
       Options         Includes
       AddHandler      server-parsed .shtml
</Location>


Q: Android - TextViews not showing up in ListView I'm having an issue to where none of my TextViews are showing up in the ListView. I'm not sure whether it is an issue with the layout or the java class itself. There are two images here, one of the application running after data had been entered into the database and one of what it is supposed to look like.
Layout for each row of data in ListView

Fragment for the ListView (Delete Button appears but not the TextViews)

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

    <TextView
        android:layout_width="123dp"
        android:layout_height="wrap_content"
        android:id="@+id/resultTeamNumber"
        android:text="Here Number"
        android:textSize="18dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:id="@+id/textPortcullis"
        android:text="Portcullis:"
        android:layout_above="@+id/textChevalFrise"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/resultPortcullis"
        android:text="Yes/No"
        android:singleLine="false"
        android:layout_below="@+id/resultTeamNumber"
        android:layout_marginLeft="110dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textChevalFrise"
        android:text="Cheval de Frise:"
        android:layout_below="@+id/resultPortcullis"
        android:layout_alignParentStart="true"
        android:singleLine="false" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/resultChevalFrise"
        android:text="Yes/No"
        android:singleLine="false"
        android:layout_below="@+id/resultPortcullis"
        android:layout_alignStart="@+id/resultPortcullis" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textMoat"
        android:singleLine="false"
        android:layout_below="@+id/textChevalFrise"
        android:layout_alignParentStart="true"
        android:text="Moat:" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/resultMoat"
        android:text="Yes/No"
        android:singleLine="false"
        android:layout_below="@+id/resultChevalFrise"
        android:layout_alignStart="@+id/resultChevalFrise" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textRamparts"
        android:text="Ramparts:"
        android:singleLine="false"
        android:layout_below="@+id/textMoat"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/resultRamparts"
        android:text="Yes/No"
        android:singleLine="false"
        android:layout_above="@+id/textDrawbridge"
        android:layout_alignStart="@+id/resultMoat" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textDrawbridge"
        android:text="Drawbridge:"
        android:singleLine="false"
        android:layout_below="@+id/textRamparts"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/resultDrawbridge"
        android:text="Yes/No"
        android:singleLine="false"
        android:layout_below="@+id/resultRamparts"
        android:layout_alignStart="@+id/resultRamparts" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textSallyPort"
        android:text="Sally Port:"
        android:singleLine="false"
        android:layout_below="@+id/textDrawbridge"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/resultSallyPort"
        android:singleLine="false"
        android:layout_below="@+id/resultDrawbridge"
        android:layout_alignStart="@+id/resultDrawbridge"
        android:text="Yes/No" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textRockWall"
        android:text="Rock Wall:"
        android:singleLine="false"
        android:layout_alignTop="@+id/resultPortcullis"
        android:layout_toEndOf="@+id/resultPortcullis"
        android:layout_marginStart="34dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/resultRockWall"
        android:singleLine="false"
        android:text="Yes/No"
        android:layout_marginStart="46dp"
        android:layout_above="@+id/resultRockTerrain"
        android:layout_toEndOf="@+id/textRockTerrain" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textRockTerrain"
        android:text="Rock Terrain:"
        android:singleLine="false"
        android:layout_below="@+id/textRockWall"
        android:layout_alignStart="@+id/textRockWall" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/resultRockTerrain"
        android:singleLine="false"
        android:text="Yes/No"
        android:layout_alignBottom="@+id/textRockTerrain"
        android:layout_alignStart="@+id/resultRockWall" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textLowBar"
        android:text="Low Bar:"
        android:singleLine="false"
        android:layout_above="@+id/resultRamparts"
        android:layout_alignStart="@+id/textRockTerrain" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/resultLowBar"
        android:singleLine="false"
        android:text="Yes/No"
        android:layout_below="@+id/resultRockTerrain"
        android:layout_alignStart="@+id/resultRockTerrain" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:background="@color/colorPrimary"
        android:text="Delete"
        android:id="@+id/buttonDelete"
        android:layout_below="@+id/textLowBar"
        android:layout_toEndOf="@+id/textLowBar"
        android:layout_above="@+id/resultSallyPort" />
</RelativeLayout>

ScoutFragment.java
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

/**
 * A simple {@link Fragment} subclass.
 */
public class ScoutFragment extends Fragment {

    FloatingActionButton addDataScout;
    ListView eListScoutInfo;
    SQLiteDatabase sqLiteDatabase;
    DatabaseHelper databaseHelper;
    Cursor cursor;
    ListScoutInfoAdapter listScoutInfoAdapter;

    public ScoutFragment() {
        // Required empty public constructor
    } //End of ScoutFragment

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_scout, null, false);
        view.setBackgroundColor(Color.WHITE);
        eListScoutInfo = (ListView) view.findViewById(R.id.listScoutInfo);
        listScoutInfoAdapter = new ListScoutInfoAdapter(getActivity().getApplicationContext(), R.layout.row_layout);
        eListScoutInfo.setAdapter(listScoutInfoAdapter);
        databaseHelper = new DatabaseHelper(getActivity().getApplicationContext());
        sqLiteDatabase = databaseHelper.getReadableDatabase();
        cursor = databaseHelper.getInformation(sqLiteDatabase);

        //Checks if information is available in cursor
        if(cursor.moveToFirst()){
            do {
                //Declare all strings
                String teamNumber, portcullis, chevalFrise, moat, ramparts, drawbridge, sallyPort, rockWall, rockTerrain, lowBar;

                //Get strings from cursor
                teamNumber = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_NUMBER));
                portcullis =  cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_PORTCULLIS));
                chevalFrise = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_CHEVAL_FRISE));
                moat = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_MOAT));
                ramparts = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_RAMPARTS));
                drawbridge = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_DRAWBRIDGE));
                sallyPort = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_SALLY_PORT));
                rockWall = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_ROCK_WALL));
                rockTerrain = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_ROCK_TERRAIN));
                lowBar = cursor.getString(cursor.getColumnIndex(DatabaseContract.NewDataInfo.COL_LOW_BAR));

                //Get methods from DatabaseProvider
                DatabaseProvider databaseProvider = new DatabaseProvider(teamNumber, portcullis, chevalFrise, moat, ramparts,
                        drawbridge, sallyPort, rockWall, rockTerrain, lowBar);

                //Pass objects to add method
                listScoutInfoAdapter.add(databaseProvider);
                listScoutInfoAdapter.notifyDataSetChanged();
            } while (cursor.moveToNext());
        } //End of if statement

        //Setups Floating Action Button
        addDataScout = (FloatingActionButton) view.findViewById(R.id.fab);
        addDataScout.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AddScoutDataFragment fragment = new AddScoutDataFragment();
                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
                fragmentTransaction.replace(R.id.fragment_container, fragment);
                fragmentTransaction.commit();
            } //End of onClick
        }); //End of setOnClickListener
        return view;
    } //End of onCreateView
} //End of class

I don't believe the issue is with database showing the data because some of the TextViews in the ListView don't even use the data from inside the database.

A: It is theme issue on your end,probably textcolor set to white in your theme change these
<item name="android:textColorPrimary">@color/white</item>
<item name="android:textColorSecondary">@color/white</item>

change it to black

A: your row_layout.xml file textview in set textcolor:
 <TextView
    android:layout_width="123dp"
    android:layout_height="wrap_content"
    android:id="@+id/resultTeamNumber"
    android:text="Here Number"
    android:textSize="18dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:textColor="@android:color/black"

/>

A: set your adapter upon listview in the last..............


Q: How to Append radio buttons to dynamic html table I have an ajax call that returns a sql query result and parses it into an html table. See below:
function CreateTableFromJSON() {
  var email = "<?php echo $user_email; ?>";
  console.log(email);
  $.ajax({
    type: 'POST',
    url: 'api.php',
    data:{
      //format:'json'
      //data:$.param({
        'userEmail': email
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      console.log("success");

      // EXTRACT VALUE FOR HTML HEADER.
      var col = [];
      for (var i = 0; i < data.length; i++) {
        for (var key in data[i]) {
          if (col.indexOf(key) === -1) {
            col.push(key);
          }
        }
      }

      // CREATE DYNAMIC TABLE.
      var table = document.getElementById('excel_tablebody2');
      var tr = table.insertRow(-1); // TABLE ROW.

      //for (var i = 0; i < col.length; i++) {
      //  var th = document.createElement("th"); // TABLE HEADER.
      //  th.innerHTML = col[i];
      //  tr.appendChild(th);
      //}

      // ADD JSON DATA TO THE TABLE AS data.
      for (var i = 0; i < data.length; i++) {
        tr = table.insertRow(-1);

        for (var j = 0; j < col.length; j++) {
          var tabCell = tr.insertCell(-1);
          tabCell.innerHTML = data[i][col[j]];
        }
      }

      // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
      var divContainer = document.getElementById("excel_table2");
      divContainer.appendChild(table);
    },
    error: function(error) {
      console.log(error);
      console.log("CreateTableFromJSON did not work.....");
    }
  });
};

I'd like to append radio buttons to the table. Specifically how can I do this for dynamic tables (undefined number of rows and or columns)?
In addition the radio button would need to relate to a specific tr as it will need to be used to send data back for that tr
The goal is to return the table based on some criteria (user email).
The table will contain data that needs to be verified using the radio buttons. Yes/No button and then sent back.
Edit
I'll add I'm unsure how to approach my overall goal.
Is it best to allow the user to update the each row by using the radio button and once done submit it all back to the server. OR have each radio button fire an individual 'update' back to the server as you progress. Live update vs bulk update?


Q: Trouble in installing Font::TTF module I failed to install the module through cpan Font::TTF.
I'm on strawberry perl 5.24, windows 8 32bit.
C:\Users\user>cpan
Loading internal null logger. Install Log::Log4perl for logging messages

There seems to be running another CPAN process (pid 5860).  Contacting...
Other job not responding. Shall I overwrite the lockfile 'C:\STRAWB~1\cpan\.lock
'? (Y/n) [y]

cpan shell -- CPAN exploration and modules installation (v2.11)
Enter 'h' for help.

cpan> o conf build_dir_reuse 0
    build_dir_reuse    [0]
commit: wrote 'C:\Strawberry\perl\lib/CPAN/Config.pm'

cpan> o conf commit
commit: wrote 'C:\Strawberry\perl\lib/CPAN/Config.pm'

cpan> exit
Lockfile removed.

C:\Users\user>cpan Font::TTF
Loading internal null logger. Install Log::Log4perl for logging messages
CPAN: CPAN::SQLite loaded ok (v0.211)
Database was generated on Fri, 15 Jul 2016 06:47:48 GMT

Running install for module 'Font::TTF'
CPAN: Digest::SHA loaded ok (v5.95)
CPAN: Compress::Zlib loaded ok (v2.069)
Checksum for C:\STRAWB~1\cpan\sources\authors\id\M\MH\MHOSKEN\Font-TTF-  1.05.tar.
gz ok
CPAN: Archive::Tar loaded ok (v2.06)
CPAN: File::Temp loaded ok (v0.2304)
CPAN: YAML::XS loaded ok (v0.62)
CPAN: CPAN::Meta::Requirements loaded ok (v2.140)
CPAN: Parse::CPAN::Meta loaded ok (v1.4417)
CPAN: CPAN::Meta loaded ok (v2.150005)
CPAN: Module::CoreList loaded ok (v5.20160507)
Configuring M/MH/MHOSKEN/Font-TTF-1.05.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Generating a dmake-style Makefile
Writing Makefile for Font::TTF
Writing MYMETA.yml and MYMETA.json
  MHOSKEN/Font-TTF-1.05.tar.gz
  C:\Strawberry\perl\bin\perl.exe Makefile.PL -- OK
Running make for M/MH/MHOSKEN/Font-TTF-1.05.tar.gz
  MHOSKEN/Font-TTF-1.05.tar.gz
  C:\STRAWB~1\c\bin\dmake.exe -- OK
Running make test
"C:\Strawberry\perl\bin\perl.exe" "-MExtUtils::Command::MM" "-MTest::Harness"   "-
e" "undef *Test::Harness::Switches; test_harness(0, 'blib\lib', 'blib\arch')"   t/
*.t
t/tags.t ..... Can't locate Font/TTF/OTTags.pm in @INC (you may need to   install
the Font::TTF::OTTags module) (@INC contains: C:\STRAWB~1\cpan\build\Font-TTF-1.
05-8DWSyh\blib\lib C:\STRAWB~1\cpan\build\Font-TTF-1.05-8DWSyh\blib\arch  C:/Stra
wberry/perl/site/lib C:/Strawberry/perl/vendor/lib C:/Strawberry/perl/lib .) at
t/tags.t line 5.
BEGIN failed--compilation aborted at t/tags.t line 5.
t/tags.t ..... Dubious, test returned 2 (wstat 512, 0x200)
Failed 6/6 subtests
t/ttfcopy.t .. Can't locate Font/TTF/Font.pm in @INC (you may need to install th
e Font::TTF::Font module) (@INC contains: C:\STRAWB~1\cpan\build\Font-TTF-  1.05-8
DWSyh\blib\lib C:\STRAWB~1\cpan\build\Font-TTF-1.05-8DWSyh\blib\arch C:/Strawber
ry/perl/site/lib C:/Strawberry/perl/vendor/lib C:/Strawberry/perl/lib .) at t/tt
fcopy.t line 5.
BEGIN failed--compilation aborted at t/ttfcopy.t line 5.
t/ttfcopy.t .. Dubious, test returned 2 (wstat 512, 0x200)
Failed 4/4 subtests

Test Summary Report
-------------------
t/tags.t   (Wstat: 512 Tests: 0 Failed: 0)
  Non-zero exit status: 2
  Parse errors: Bad plan.  You planned 6 tests but ran 0.
t/ttfcopy.t (Wstat: 512 Tests: 0 Failed: 0)
  Non-zero exit status: 2
  Parse errors: Bad plan.  You planned 4 tests but ran 0.
Files=2, Tests=0,  1 wallclock secs ( 0.05 usr +  0.00 sys =  0.05 CPU)
Result: FAIL
Failed 2/2 test programs. 0/0 subtests failed.
dmake.exe:  Error code 130, while making 'test_dynamic'
  MHOSKEN/Font-TTF-1.05.tar.gz
  C:\STRAWB~1\c\bin\dmake.exe test -- NOT OK
//hint// to see the cpan-testers results for installing this module, try:
  reports MHOSKEN/Font-TTF-1.05.tar.gz
Stopping: 'install' failed for 'Font::TTF'.

C:\Users\user>

A: Jiang Bo, I was also getting the same problem with the latest Strawberry Perl version (5.24.0.1). I downgraded to 5.20.3.3 / 64bit and cpan installations work fine there.


Q: Dynamically executed ARM ASM syscall with relocations from C++ I would like to call ARM/ARM64 ASM code from C++. ASM code contains syscall and a relocation to external function.
ARM architecture here is not so important, I just want to understand how to solve my problem conceptually.
I have following ASM syscall (output from objdump -d) which is called inside shared library:
 198:   d28009e8    mov x8, #0x4f                   // #79
 19c:   d4000001    svc #0x0
 1a0:   b140041f    cmn x0, #0x1, lsl #12
 1a4:   da809400    cneg    x0, x0, hi
 1a8:   54000008    b.hi    0 <__set_errno_internal>
 1ac:   d65f03c0    ret

This piece of code calls fstatat64 syscall and sets errno through external __set_errno_internal function.
readelf -r shows following relocation for __set_errno_internal function:
00000000000001a8 R_AARCH64_CONDBR19  __set_errno_internal

I want to call this piece of code from C++, so I converted it to buffer:
  unsigned char machine_code[] __attribute__((section(".text"))) =
        "\xe8\x09\x80\xd2"
        "\x01\x00\x00\xd4"
        "\x1f\x04\x40\xb1"
        "\x00\x94\x80\xda"
        "\x08\x00\x00\x54"   // Here we have mentioned relocation
        "\xc0\x03\x5f\xd6";

EDIT: Important detail - I chose to use buffer (not inline assembly etc) because I want to run extra processing on this buffer (for example decryption function on string literal as a software protection mechanism but that's not important here) before it gets evaluated as machine code.
Afterwards, buffer can be cast to function and called directly to execute machine code. Obviously there is a problem with relocation, it's not fixed automatically and I have to fix it manually. But during run-time I can't do it because .text section is read-only & executable.
Although I have almost full control over source code I must not turn off stack protection & other features to make that section writable (don't ask why). So it seems that relocation fix should be performed during link stage somehow. As far as I know shared library contains relative offsets (for similar external function calls) after relocations are fixed by linker and binary *.so file should contain correct offsets (without need of run-time relocation work), so fixing that machine_code buffer during linking should be possible.
I'm using manually built Clang 7 compiler and I have full control over LLVM passes so I thought maybe it's possible to write some kind of LLVM pass which executes during link time. Though it looks like ld is called in the end so maybe LLVM passes will not help here (not an expert here).
Different ideas would be appreciated also.
As you can see problem is pretty complicated. Maybe you have some directions/ideas how to solve this? Thanks!

A: There's already a working, packaged mechanism to handle relocations. It's called dlsym().  While it doesn't directly give you a function pointer, all major C++ compilers support reinterpret_casting the result of dlsym to any ordinary function pointer. (Member functions are another issue altogether, but that's not relevant here)


Q: Astable 555 timing circuit (0.5 Hz and 50% duty cycle) I am trying to build a timing circuit to generate a 0.5 Hz 50% duty cycle signal. In other words 1 second on, 1 second off, and so on...
I have searched a few places and found the following instructions but that did not work. http://electronicsclub.info/555timer.htm#dutycycle.
Any ideas?

A: See the description of "Better Timing" in 555 Timer Circuits.  That circuit eliminates the classic R2, adds an NPN transistor (2N3904 is fine), a new R2 just to bias the added NPN transistor (i.e. does not participate in the RC circuit), and two diodes to charge and discharge the capacitor through R1.  This gives a 50% duty cycle (as the charging and discharging is done through the same, single resistor).
From the linked site:
[]
Also from the linked site:

Better and more stable timing output is created with the addition of a
  transistor and a diode to the R-C timing network. The frequency can be
  varied over a wide range while maintaining a constant 50% duty-cycle.
  When the output is high, the transistor is biased into saturation by
  R2 so that the charging current passes through the transistor and R1
  to C. When the output goes low, the discharge transistor (pin 7) cuts
  off the transistor and discharges the capacitor through R1 and the
  diode. The high & low periods are equal. The value of the capacitor
  (C) and the resistor (R1 or potmeter) is not given. It is a mere
  example of how to do it and the values are pending on the type of
  application, so choose your own values. The diode can be any small
  signal diode like the NTE519, 1N4148, 1N914 or 1N3063, but a high
  conductance Germanium or Schottky type for the diode will minimize the
  diode voltage drops in the transistor and diode. However, the
  transistor should have a high beta so that R2 can be large and still
  cause the transistor to saturate. The transistor can be a TUN
  (europe), NTE123, 2N3569 and most others.

A: It's impossible to get a 50% output from a 555 with the conventional 2 resistor 1 capacitor astable arrangement.
The easiest way is to use a CMOS 555 and to use the circuit shown on the title page of:
http://datasheets.maximintegrated.com/en/ds/ICM7555-ICM7556.pdf
The next easiest way, and the way to achieve any duty cycle from <1% to >99% is to use diode steering around the astable's resistors
The way to get the most accurate 50% is to set the 555 to output twice the frequency you want and then to do a divide-by-two on its output with a "D" type flip-flop.

A:

In this modified astable multivibrator circuit the forward voltage drop of the diode D1 is always ignored, and the timing formulas are given as
$$ t_1 = \ln(2)R_1C_1, \quad t_2 = \ln(2)R_2C_1. $$
If you take \$R_1 = R_2\$ and ignore the diode voltage drop, you achieve %50 duty cycle. But, what happens if we don't ignore the diode voltage drop?
Suppose that the forward voltage drop of D1 is \$V_D\$. The voltage at pin 5 will be \$\dfrac{2}{3}V_{cc}\$.
The most general form of capacitor charging equation is
$$ v_c(t) = V_s + \left[ v_c(t_0) - V_s \right] e^{-\dfrac{t-t_0}{RC}}, \quad t\ge t_0. $$
If we rearrange the terms to get the time difference, we get
$$ \Delta t = t - t_0 = RC \ln \left[ \dfrac{V_s - v_c(t_0)}{V_s - v_c(t)} \right] . $$
Where, \$v_c(t)\$ is the function of capacitor voltage, \$V_s\$ is the source voltage.
During the on-time, the capacitor C1 will charge from \$\dfrac{1}{3}V_{cc}\$ to \$\dfrac{2}{3}V_{cc}\$ over R1. The supply voltage this R-C network sees is \$V_{cc}-V_D\$.
$$ t_1 = R_1C_1 \ln \left[ \dfrac{V_{cc} - V_D - \dfrac{1}{3}V_{cc}}{V_{cc} - V_D - \dfrac{2}{3}V_{cc}} \right] = R_1C_1 \ln \left[ \dfrac{\dfrac{2}{3}V_{cc} - V_D}{\dfrac{1}{3}V_{cc} - V_D} \right] = R_1C_1 \ln \left[ 1 + \dfrac{V_{cc}}{V_{cc} - 3V_D} \right] $$
During the discharge, D1 has no effect. So, similarly, \$t_2\$ will be
$$ t_2 = R_2C_1 \ln \left[ \dfrac{V_{cc} - \dfrac{1}{3}V_{cc}}{V_{cc} - \dfrac{2}{3}V_{cc}} \right] = \ln(2) R_2C_1. $$
Then the period of the oscillation is
$$ \boxed{T = t_1 + t_2 = R_1C_1 \ln \left[ 1 + \dfrac{V_{cc}}{V_{cc} - 3V_D} \right] + \ln(2) R_2C_1}. $$
And the frequency is
$$ \boxed{f = \dfrac{1}{T} = \dfrac{1}{t_1 + t_2} = \dfrac{1}{R_1C_1 \ln \left[ 1 + \dfrac{V_{cc}}{V_{cc} - 3V_D} \right] + \ln(2) R_2C_1}}. $$
(Adapted from this question.)

Compensation of The Error Due To Diode Forward Voltage Drop
We want to make the on and off times are equal. That is
$$ t_1 = t_2. $$
Then,
$$
R_1C_1 \ln \left[ 1 + \dfrac{V_{cc}}{V_{cc} - 3V_D} \right] = \ln(2) R_2C_1,\\
\ln \left[ 1 + \dfrac{V_{cc}}{V_{cc} - 3V_D} \right] = \dfrac{R_2}{R_1} \ln(2),\\
\boxed{R_1 = R_2 \dfrac{\ln(2)}{\ln \left[ 1 + \dfrac{V_{cc}}{V_{cc} - 3V_D} \right]}
\quad\quad \text{or} \quad\quad
R_2 = R_1 \dfrac{\ln \left[ 1 + \dfrac{V_{cc}}{V_{cc} - 3V_D} \right]}{\ln(2)}}.
$$
You have to choose \$R_1\$ and \$R_2\$ proportional to each other like this in order to achieve precisely symmetrical 50% duty cycle.

A: Do this with a cheap and small microcontroller, like the PIC 10F200.  That only requires two parts, the micro, which is available in a SOT-23 package, and the bypass cap.
Then get a 666 555 timer from your favorite museum gift shop and glue it over the PIC and cap to show the world that it's done with a 555 timer.  Those that don't look too hard will be scratching their heads how you got the accuracy so high, and the drift and power consumption so low.
For extra credit, add a few more parts to really make them scratch their heads.  The museum gift shop will certainly have 741 opamps too.  Get the ones in a can for the best nostalgic look.

A: Before designing more complex things please take a look page 16 http://www.ti.com/lit/ds/symlink/lmc555.pdf

A:
Keeping both charging and discharging time of capacitor equal . Getting around 0.49 - 0.5 Hz with 50% duty cycle .

A: Your calculations are wrong, but not that wrong. Using equal 65k resistors should give you a 33% duty cycle (t1 = .7 R1 C, t2 = .7 (R1 + R2) C). Your computations were carried out correctly given that your formulas were wrong, and the values you used should give a total period of 3 seconds rather than two. The change in duty cycle suggests that you've either got one of your resistor values wrong (and you need to measure them), or you wired the chip wrong. Your overall timing suggests that your capacitor is way off. I suggest that you're using a 22 nF capacitor rather than a 22 uF.

A: Using this calculator, I was abler to compute the following values:
R1 = 1K
R2 = 360K
C1 = 4 µF

Frequency = 0.5 Hz
Period = 1.999s
50.07% duty cycle
1.001s on, 997.2 ms off

which is pretty much spot on.  However 360K is not as standard resistor value; the closest is 357K.  This gives:
R1 = 1K
R2 = 357K
C1 = 4 µF

Frequency = 0.505 Hz
Period = 1.982s
50.07% duty cycle
992.37 ms on, 989.6 ms off

However worrying about the difference caused by the 3K is pretty much irrelevant, because you have to take into consideration the tolerance of the components.  Assuming you are using 1% resistors, changing the value of R1 by 1% has little effect, and changing the value of R2 by 1% is about the change from 350K to 357K shown above.
The problem is the capacitor C1.  Many capacitors have a tolerance of ±20%.  This means the 4 µF cap could vary from 3.2 µF to 4.8 µF which will  cause the period to vary from 1.586 s to 2.378 s.  Luckily this can be compensated by changing R2; 3.2 µF along with R2 = 450K reverts to the original timing shown above, as does 4.8 µF along with R2 = 300K.  So bottom line, once you pick a capacitor, you are going to have to adjust R2 to give you the period you need.
I suggest using a 500K pot for R2 to start with, adjust until you get the required period, then measure the setting of the pot and replace it by a fixed resistor.

A: Follow this image:

Choose R1=R2 and put a diode in parallel with R2, with cathode facing capacitor C.
T1 will be= 0.693 x R1 x C
T2 will be= 0.693 x R2 x C

A: LM567 would be another chip well suites for this application. It has a dedicated VCO with frequency range from 0.01Hz to 500kHz, 50% duty cycle output. For 0.5Hz output, use a 10uF ceramic timing resistor (X5R or X7R), and about 180kOhm timing resistor. To trim the frequency, use e.g. 150k fixed resistor in series with a 50k trimmer.
The following circuit should work:

simulate this circuit – Schematic created using CircuitLab

A: I built the circuit in question in this thread using the 555 in the astable mode which included using a 1uf cap for C1, R1 was 100k, R2 was 1Meg, no cap at pin 5 (control voltage), no diode across R2 as suggested to lower the duty cycle.
The results were a 53% duty cylce at .5 Hz (Or very close to it). Supply voltage was 12vdc but there was an 8 volt overshoot on rise that was 12 microseconds in duration, so I added a .01uf ceramic disc cap across output pin 3 and ground, it created a very slight charge curve at the top but eliminated the spike, this was expected.
I used this to control another circuit I built that uses another 555 and an LM339 (or LM393) op amp.
It uses a 1 Meg pot connected to pins 2 & 6 (between - and + on the supply voltage with the wiper connected to pins 2 & 6 on the second 555) this was to be able to adjust the frequency on the second 555 (output pins 3 & 5 were not used in the second circuit), then I used a 50k pot at the negative input of the op amp to adjust the duty cycle. The wiper of this pot connected to the negative side of the op amp. The positive input of the op amp came from pin 7 on the second 555.
Note, you can raise the value of R2 or lower the value of R1 to increase the duty cycle (on the first 555 being discussed in this thread).
End result for final output was "off for close to 1/2 second, then oscillated at 4 hZ while "on" or in the "high" state. I used only one output from the op amp. I used an NMOS for output of the op amp to be "on" while output was high, then used a PMOS for an "on" output while in the low state.
This create an alternating output from just one op amp output for approximately 1/2 second (Based on the frequency and duty cycle of the first 555), then off for approximately 1/2 second.
I am able to adjust the duty cycle and frequency at will but the first 555 is fixed at a 53% duty cycle at .5 Hz
The second circuit with the second 555 and an op amp will produce 188 kHz, I was quite surprised that it would go that high, I was expecting about 125 kHz at best. The waveforms are pretty much pointed rather than anything resembling a square wave but it works. Anything higher than 188 kHz was too much, the 555 wouldn't cycle any faster than that. The MOSFETS and op amp could handle it but not the 555 that I used (NE555N) At least that was my conclusion based on the process of elimination and further testing with various resistors and caps.
I use the second circuit as a variable frequency and variable duty cycle driver to test new designs for other circuits. It uses a 470nf cap for full potential on the high end of the frequency and a 47nf cap for the low end. It will adjust from .3 to 99% duty cycle and from .3 Hz to 188 kHz.
Hope this helps someone else. I can send the circuit diagram to anyone who wants it or I can post a link to it if there's an interest.
Final note, this combined circuit only draws 56mA with a 36mA load (56 mAh average). I used a data logger over a 10 minute span at 1 second intervals for the sample rate, then downloaded it onto an EXCEL spreadsheet for analysis.
I used to design circuits twenty years ago but things have changed a lot since then so I'm having to learn many new devices from scratch. So, If I've made any mistakes in explaining this, please feel free to point them out!!  :-)
Thanks!!!
Joe


Q: Ends of plot get cut off About 1/10 of one of my plots gets cut off on both sides, no matter how xmin and xmax are set. How can this be prevented?
\documentclass{standalone}
\usepackage{tikz,pgfplots}

\begin{document}

        \begin{tikzpicture} \pgfplotsset{scale only axis}
        \begin{axis}[ymin=0,xmin=0,xmax=1,
        axis y line*=left,
        width=13cm,height=7cm,tick align=center]
        \addplot[smooth]
        coordinates{
            (0.0001,2)
            (0.999999,2)
        };
        \end{axis}

        \begin{axis}[axis y line*=right,
        axis x line=none,width=13cm,height=7cm]

        \addplot[dotted]
        coordinates{
            (0.0001, 1)
            (0.99999,1)};
        \end{axis}
        \end{tikzpicture}

\end{document}


Q: error: bind message supplies 1 parameters, but prepared statement "" requires 0 I have a table 'article' with column 'content' .I want to query Postgresql in order to search for a string contained in variable 'temp'.This query works fine-
pool.query("select * from article where upper(content) like upper('%some_value%')");

But when I use placeholder $1 and [temp] in place of some_value , I get the above error -
pool.query("select * from article where upper(content) LIKE upper('%$1%')",[temp] );

Note - Here $1 is a placeholder and should be replaced by the value in [temp] , but it treats '%$1%' as a string , I guess. Without the quotes ' ' , the LIKE operator doesn't work. I have also tried the query -
pool.query("select * from article where upper(content) LIKE upper(concat('%',$1,'%'))",[temp] );

to ensure $1 is not treated as a string literal but it gives the error -
    error: could not determine data type of parameter $1

A: pool.query(
  "select * from article where upper(content) LIKE upper('%' || $1 || '%')",
  [temp]
).then( res => {console.log(res)}, err => {console.error(err)})

This works for me. I just looked at this Postgres doc page to try and understand what concat was doing to the parameter notation. Can't say that I understand the difference between using || operators and using concat string function at this time.

A: The easiest way I found to do this is like the following:
// You can remove [0] from character[0] if you want the complete value of character.
  database.query(`
    SELECT * FROM users
    WHERE LOWER(users.name) LIKE LOWER($1)
    ORDER BY users.id ASC`,
    ["%" + character[0] + "%"]
  );

// [%${character}%] string literal alternative to the last line in the function call.

There are several things going on here, so let me break each line it down.

*

*SELECT * FROM users

*

*This is selecting all the columns associated with table users

*WHERE LOWER(users.name) LIKE $1

*

*This is filtering out all the results from the first line so that where the name(lowercased) column of the users table is like the parameter $1.

*ORDER BY users.id ASC

*

*This is optional, but I like to include it because I want the data returned to me to be in ascending order (that is from 0 to infinity, or starting low and going high) based on the users.id or the id column of the users table. A popular alternative for client-side data presentation is users.created_at DESC which shows the latest user (or more than likely an article/post/comment) by its creation date in reverse order so you get the newest content at the top of the array to loop through and display on the client-side.

*["%" + character + "%"]

*

*This part is the second argument in the .query method call from the database object (or client if you kept with that name, you can name it what you want, and database to me makes for more a sensical read than "client", but that is just my personal opinion, and it's highly possible that "client" may be the more technically correct term to use).
The second argument needs to be an array of values. It takes the place of the parameters inserted in the query string, for example, $1 or ? are examples of parameter placeholders which are filled in with a value in the 2nd argument's array of values. In this case, I used JavaScript's built-in string concatenation to provide a "includes" like pattern, or in plain-broken English, "find me columns that contain a 'this' value" where name(lowercased) is the column and character is the parameter variable value. I am pulling in the parameter value for the character variable from req.params (the URL, so http://localhost:3000/users/startsWith/t), so combining that with % on both ends of the parameter, it returns me all the values that contain the letter t since is the first (and only) character here in the URL.

I know this is a VERY late response, but I wanted to respond with a more thorough answer in case anyone else needed it broken down further.

A: In my case :
My variable was $1, instead of ?1 ...
I was customizing my query with @Query


Q: Errors only when running shiny application on server - debug I have written a small application in shiny. I have the following files:
global.R, server.R and ui.R
In the global.R file, I load my data. I read data from three different csv files.
a.csv, b.csv and c.csv and I use merge to join a.csv and b.csv and another merge to join a.csv and c.csv
In the ui.R file, I have the layout for some filters. In the shinydashboard, I have tabItems, tabPanels containing selectInput and sliderInput for the filters.
In the server.R file, I have the implementation. One functionality is that based on the filters, I show a table with some values. If the user selects a row, I activate another tab with more details on the selected row (eg, graphs, tables etc related to the selected row)
This whole thing works perfectly when I run it on my machine using RStudio. When I move the code to the shiny server, I get the first tab layout, the functionality to activate second tab on selection all working. However in the second tab, I cannot see the table, and I get an error for the graphs.
Error: 'from' cannot be NA, NaN or infinite.
I have no clue why I cannot see any data on the tab when I run the application on the server. I suspect maybe there is some problem in the merge. I want to debug and find the problem. I wanted to know how I can debug since I run this on the server using a web browser and all I can see on the browser is a line Error: 'from' cannot be NA, NaN or infinite and blank table.
Can someone give some inputs on debugging to find the problem. Thanks

A: I was able to figure out the problem. The problem was with the package version of DT on the server. The package version of DT on the server was 0.1 and that version has some bugs (based on this post: https://github.com/rstudio/DT/issues/206)
I was able to get the package version updated to 0.2 and all worked fine.
The problem was with using input$table_rows_selected with the old version of DT package with selection = 'single' as a parameter. Moving to 0.2 version of DT package resolved the problem.


Q: Detect click when the allow Button in the notification alert permission is tapped
I'm developing this iOS app with SwiftUI.
How I can detect when the user clicks the allow button of the Notification permission alert? It should happen only one time and I need to take the user to a specific tab the first time he tapped the button. Is this possible?

A: you can add the attribute onclick="location.href='https://google.com';".
but could you post codesnippets? and do you use javascript and php?

A: I found a solution. To create this behaviour, I simply saved in a UserDefault a Bool value.
 func registerForPushNotifications() {
    UNUserNotificationCenter.current()
        .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in
            print("Permission granted: \(granted)")

            self?.userDefault.set(granted, forKey: "notificationGranted")

            guard granted else {
                return
            }

            self?.getNotificationSettings()
        }
}

      func getNotificationSettings() {
    UNUserNotificationCenter.current().getNotificationSettings { settings in
        print("Notification settings: \(settings)")

        guard settings.authorizationStatus == .authorized else {
            return
        }
        // Saving the value to permit to take the user to the Notification screen only the first time
        if (self.userDefault.value(forKey: "permissionPopUpIsShowed") == nil) {
            self.userDefault.set(true, forKey: "permissionPopUpIsShowed")
        }

        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}

In the Content View inside the onAppear method you can do this:
                        if appDelegate.userDefault.bool(forKey: "permissionPopUpIsShowed") == true && appDelegate.userDefault.bool(forKey: "notificationGranted") == true {
                        tabSelection = .notifications
                        appDelegate.userDefault.set(false, forKey: "permissionPopUpIsShowed")
                    }

In this way you will be able to select a new view (through the tabSelection) and obtain this behaviour only once (when the notification permission popUp is showed).


Q: JS + POST + FORM Здравствуйте.
Объясню на примере:
Пользователь заходит на страницу index.html с таким содержанием:
<form name="buy" action="script.php" method="post">
<select name="type[]" id="type" multiple>
<option value="0">Планшет</option>
<option value="1">Телевизор</option>
<option value="2">Телефон</option>
</select>
<input type="submit" value="OK">
</form>

Выбирает из выпадающего списка "Телевизор" и "Телефон" и нажимает "OK".
Страница script.php принимает данные и в случае ошибки выдаёт исходную форму обратно. JS после этого исходя из POST данных добавляет selected к полю "Телевизор" и полю "Телефон".
Как такое можно было бы реализовать (в смысле JS составляющую - т.е. интересует исключительно сохранение выбранных полей после обновления страницы)?
Наработки:
Нашел вот такой скрипт:
<script type="text/javascript">
<!--
/**
* Сохраняем форму. Функция принимает ссылку на форму. Форма должна иметь
* уникальный аттрибут ID.
*/
function saveFormSession(form) {
  if(!form||!form.id||!/^[^;=]+$/.test(form.id)) return;
  var data="", tok, el, safe_name;
  for(var i=0; i<form.elements.length; i++) {
    if((el=form.elements[i]).name==""||el.getAttribute("skip_form_save")!=null) continue;
    safe_name=el.name.replace(/([)\\])/g, "\\$1");
    switch(el.type) {
      case "text":
      case "textarea": tok="v("+safe_name+"):"+el.value.replace(/([|\\])/g, "\\$1")+"||"; break;
      case "radio":
      case "checkbox": tok="s("+safe_name+"):"+(el.checked? "1": "0")+"||"; break;
      case "select-one": tok="i("+safe_name+"):"+(el.selectedIndex)+"||"; break;
      default: tok="";
    }
    data+=tok;
  }
  if(data>=4000) return alert("Can't save form into cookie, to much data...");
  document.cookie="ses"+form.id+"="+escape(data);
}
/**
* Восстановить значение формы. Форма должна иметь уникальный атттрибут ID.
*/
function restoreFormSession(form) {
   if(!form||!form.id||!/^[^;=]+$/.test(form.id)) return false;
   var strt, end, data, nm, dat;
   if((strt=document.cookie.indexOf("ses"+form.id))<0) return false;
   if((end=document.cookie.indexOf(";", strt + form.id.length + 3))<0) end=document.cookie.length;
   data=unescape(document.cookie.substring(strt + form.id.length + 4, end)).split("||");
   for(var i=0; i<data.length-1; i++) {
      nm=/^[vsi]\(((?:[^)\\]|(?:\\\))|(?:\\\\))+)\)\:/.exec(data[i]);
      nm[1]=nm[1].replace(/\\([)\\])/g, "$1");
      dat=data[i].substr(nm[0].length).replace(/\\([|\\])/g, "$1");
      switch(data[i].charAt(0)) {
        case "v": form.elements[nm[1]].value=dat; break;
        case "s": form.elements[nm[1]].checked=(dat=="1"? true: false); break;
        case "i": form.elements[nm[1]].selectedIndex=dat; break;
      }
   }
}
//-->
</script>

Но он не работает с multiple. Как заставить его работать с multiple?
A: Если данные формы передаются через form submit с перезагрузкой страниц то заполнение формы следуе провести через php:
if ($error) {
    echo '
    <form name="buy" action="script.php" method="post">
        <select name="type[]" id="type" multiple>
            <option value="0"';
        if (array_search('0',$_POST['type'])) echo ' selected';
        echo '>Планшет</option>
            <option value="1"';
        if (array_search('1',$_POST['type'])) echo ' selected';
        echo '>Телевизор</option>
            <option value="2"';
        if (array_search('2',$_POST['type'])) echo ' selected';
        echo '>Телефон</option>
        </select>
        <input type="submit" value="OK">
    </form>';
}


Q: Python destroying content to save memory I have a class to get a webpage's html and do some things with it
import requests

class A(object):
    def __init__(self, url):
        self.r = requests.get(url)
        self.html = self.r.text
        #other things

class B(A):
    def __init__(self,url):
        super(B,self).__init__(url)
        #other things

I am going to instantiate this class hundreds of thousands of times, like so
for url in many_urls:
    page = B(url)
    #other things

how can I make sure that the content like page.html and other attributes get deleted and aren't kept in memory to slow it down?

A: The html will be held in memory for as long as the object that references it exists.
If your for loop does not assign the B object to any other variable, then each time you re-assign page the previously created B object will become eligible for garbage collection, and the html will be removed from memory at the same time.
If you are retaining references to each of your B objects you will slowly fill up your memory, but if you allow them to be garbage collected you should be fine.

A: You can use del page or page = None, both statements release the content for garbage collection. This makes sense if your for-loop kernel is memory critical or you are using object that bring their own memory management (like numpy.ndarray).
Also note that variables "bleed" out of the scope of for-loops. That means that the page from the last iteration will be present until the current scope is terminated (usually at the end of the function/method).


Q: Algorithm prints length of string rather than number of Cs and Gs in it I am new to Java and currently learning it in a 4 week course. I am working on on an assignment to find all of the Cs and Gs in a string named dna, and then divide the number of Cs and Gs by dna. I have written a small program, and it compiles with no syntax errors, but when I run it, all that is printed out is the length of dna and then 1(The output of the dividing part).
My code:
public static void cgRatio (String dna) {
    int counter = 0; // counts how many Cs and Gs
    int index = 0; // start looking from index 0
    while (dna.indexOf("C") != -1 && counter != dna.length()) { // while dna is not finished and you can find C in dna
        index = dna.indexOf("C", index); // Start looking from last index
        if (index != -1) {
            counter++;
        }
        else {
            break;
        }
    }
    System.out.println("Number of C in dna: " + counter);

    System.out.println("Gene cg ratio: " + (counter / dna.length()));
}

If anyone can help that would be great and appreciated, thanks!

A: The problem is that the second argument to indexOf is the first index in the string that it searches.

Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

Once it finds the first "C", it will then continue to always find that same "C" in the first index it looks in. You need to change your code to this:
index = dna.indexOf("C", index + 1);

To start from the first character after the "C" that you already found. You should also change the initial index to -1 so that it starts from the first character.

A: There are a few problems with your code:

*

*It uses counter as the number of cs in your dna string when it is really equal to dna.length(). This causes the ratio to be 1 if there are any cs at all, or 0 if there are none.

*There should be a variable that keeps track of how many cs there are in the string and how many gs there are (as seen in the above bullet, counter cannot be used for this.)

*As resueman said, this line:
index = dna.indexOf("C", index); should be changed to: index = dna.indexOf("C", index + 1);, or else the index will remain the same (it will always be equal to the index of the first c in the string.)

*A while loop really is not all that well suited to this kind of thing; instead, a for loop should be used.

*The ratio should be a double, not an int since doubles have more precision (they can be decimals.)

Here's code I came up with that works:
public static void cratio(String dna) {
    int c = 0;
    int g = 0;
    for(int i =0; i < dna.length(); i++) {
        if((dna.charAt(i) == 'c') || (dna.charAt(i) == 'C')) c++;
        if((dna.charAt(i) == 'g') || (dna.charAt(i) == 'G')) g++;
    }
    System.out.println("Number of 'C's in DNA: " + c + " and number of 'G's in DNA: " + g);
    int length = dna.length();
    double ratio = (double) (c+g)/length * 100;
    System.out.println("The ratio of 'C's and 'G's to the length of the DNA chain is: " + ratio + "%.");
}

If you have any questions, just let me know!


Q: iOS Take or Select Photo The camera app on iOS allows one to take a photo, but also has the button to the left that allows one to browse the photo album.
When using the UIImagePickerController I can only tell them to either do one or the other.
So, rather than making a custom camera view, or even a custom overlay to add these abilities, I'll ask if there isn't some sort of flag I'm missing to allow this use case.

A: When invoking it, you choose which one you want. There isn't a way to get exactly the same functionality as the camera app unless you, as you said, make a custom view for it. But wherever you want to invoke this, you could provide the options for either choosing a photo or taking one at that point.
You'll notice other apps that either let you take a photo or choose one from your library give you those as separate options within their UI.


Q: parity bit and error detection I have faced that in my computer architecture course at university.
I can't understand the parity bit; Why it has two kinds of even and odd.
Can anyone give me clear explain about parity codes?

A: A 'parity bit' is a method of error checking. Imagine that you need to send 8 bits over a connection and determine whether they got through right. You could try sending it twice, that way if there is an error, the receiver will know because the two messages differ. However, this requires two times the bandwidth, which is too much. So often every byte (8 bits) will also have a parity bit. You count up the number of ones in the byte. If it is odd, the parity bit is one. If it is even, the parity bit is zero. That way if there is any single error the receiver will know and only one eighth the extra bandwidth is needed. Examples:
Data: 01001001  3 ones, parity bit 1
Data: 00110101  4 ones, parity bit 0

If receiver gets 00111101 and parity bit 0, it will know that there is some corruption.
Of course if there are two errors in the same byte there will be no way to detect this - example if original is 00000001 and received is 00000010 - but this is considered to be rare enough to not worry for most applications.

A: The first sentence of the Wikipedia article is clear enough, and so is the second paragraph... But ohwell.
Given a word of n bits, with n-1 bits to check parity on and 1 bit of parity, the parity bit will be set to:

*

*1 if the number of bits set to 1 is odd, 0 otherwise (even parity);

*0 if the number of bits set to 1 is even, 1 otherwise (odd parity).

Example: 1101011x where x is the parity bit. There are 5 bits set to 1, therefore an odd number: x will be set to 1 (even parity) or 0 (odd parity).