id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23526900
|
Now, here is what I want, on submitting form I want that information to also be stored in the cloud SQL database. What steps will accomplish that?
A: Posing an example of a solution I have working. I modified Mogsdad's script to use the most up to date parameters & connection function, and fixed the syntax errors.
//Event is automatially passed on form submission when executed as a trigger.
//It contains objects that the user submitted
function writeToCloudSQL(event) {
//Note we get subname from the 'Instance Connection Name' of the Overview tab in the CloudSQL portal
var subname = 'see image';
var user = 'user';
var userPwd = 'pwd';
var db = 'db_name';
var dbUrl = 'jdbc:google:mysql://' + subname + '/' + db;
var conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
var stmt = conn.prepareStatement('INSERT INTO tbl_users (Timestamp, DL_ID, DOB, Last4SSN, HTMLGathered) values (NOW(), ?, ?, ?, \'No\');');
stmt.setString(1, event.namedValues['DL_ID']);
stmt.setString(2, event.namedValues['DOB']);
stmt.setString(3, event.namedValues['Last4SSN']);
stmt.execute();
}
Locating the subname:
Locating the subname
Read more about the Event parameter here:
https://developers.google.com/apps-script/guides/triggers/events
Read more about the connection string here:
https://developers.google.com/apps-script/reference/jdbc/jdbc#getCloudSqlConnection(String,String,String)
Also be sure you've allowed network access to google scripts
https://developers.google.com/apps-script/guides/jdbc?hl=en#using_jdbcgetconnectionurl
A: The normal data flow for a Google Form that is accepting responses and replicating them to a Spreadsheet looks like this:
You've got two opportunities for a Form Submission Trigger to replicate the form responses in your Cloud SQL database; you can either trigger from the Google Form Form submit event or the Google Sheets Form submit event.
Either way, you will have a script that gets called for every form submission, and an event object that contains the response values. Your trigger function should use the JDBC to connect to the database - that link includes an intro that walks you through the highlights.
Example
Say we have a form asking two questions, "Name" and "Age". That would result in 3 columns in our spreadsheet; "Timestamp" plus one for each question.
To match that, we have a Cloud SQL database set up with the same three columns.
A Google Sheets Form submit trigger function that wrote to a Cloud SQL database would look like this untested code:
// Replace the variables in this block with real values.
var address = 'database_IP_address';
var user = 'user_name';
var userPwd = 'user_password';
var db = 'database_name';
var dbUrl = 'jdbc:mysql://' + address + '/' + db;
// Receive form response and replicate to a row in SQL table
function handleFormSubmit( event ) {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(Timestamp, Name, Age) values (?, ?, ?)');
stmt.setString(1, event.namedValues['Timestamp']);
stmt.setString(2, event.namedValues['Name']);
stmt.setString(3, event.namedValues['Age']);
stmt.execute();
}
A: Zapier with their SQL Server and Google Sheets integrations can do this. I'm not affiliated.
https://zapier.com/apps/sql-server/integrations
A: If you don't want to roll your own solution, SeekWell lets you automatically send data from SQL to Sheets and can also sync changes from Sheets back to a database. Apps Script can do pieces of this, but I found it buggy and limited for our use case, so I built something else. There are both free and paid plans.
Disclaimer: I built this.
| |
doc_23526901
|
I used the TransactionScope with Dapper and it worked well. I could use Tranq to manage DB transactions, but would like to use something like TransactionScope to manage online operations.
Relatively new to F#, I don't know if there is anything that is equivalent to
using (var trans = new TransactionScope())
{
...//operations
trans.Complete();
}
If the line-to-line translating from C# to F# approach is wrong, then is there any more "functional way" of managing transactions?
A: F# has a similar using block to C#.
using (new Thing()) (fun x -> x.DoStuff ... )
But there is also a use binding in F#, which works just like let except it calls Dispose when the object goes out of scope. It's not too hard to make a new type that wraps TransactionScope and calls Complete when it's disposed if it hasn't been rolled back by code...
It would also be possible to make a workflow builder take care of transactions.
However, you might be better off using a database layer such as Entity Framework which handles your transactional needs.
| |
doc_23526902
|
//.....
var n=0;
$("#b1").click(function(){
document.getElementById("b1").disabled = true;
$("td").removeClass();
for (var i=0; i<25; i++)
{
var z=$("td").eq(i)
z.text(Math.floor((Math.random() * 10) ))
if (z.text()<5)
{
z.addClass("linkClass")
}
else
{
z.addClass("linkClass2")
}
}
$("td").click(function(){
n++;
if ($(this).hasClass("linkClass"))
{
$(this).removeClass()
$(this).text(parseInt($(this).text())-1);
$(this).addClass("linkClass2")
}
else
{
$(this).removeClass()
$(this).text(parseInt($(this).text())+1);
$(this).addClass("linkClass")
}
if (n==10)
{
alert("Ten times clicked");
document.getElementById("b1").disabled = false;
n=0;
}
classes linkClass and linkClass2 are just changing the background color of the cell. Any ideas?
A: You should move $("td").click(function(){ out from $("#b1").click(function(){ because each time when you click button you bind one more click on td so it performs several clicks in one time
| |
doc_23526903
|
System.out.println("This is the not equal to sign\n≠");
to appear (when run) as
This is the not equal to sign
≠
not to appear as
This is the not equal to sign
?
Is there any way to do this? I tried using windows character map, copied the symbol here, and in my code, but after changing encoding to UTF-8 and inserting it, it comes up as ? when run...
What can be done? Thanks in advance for answers to this utterly simple question
A: Set character encoding to UTF-8, pass this vm argument, if your text editor already uses UTF-8 or supports this character
-Dfile.encoding=UTF-8
A: As @Tobias Brandt says, you could use: \u2260
And btw also @Crozin is right about your console configuration
Like this
System.out.println("This is the not equal to sign \n\u2260");
A: There are five potential issues here:
1) In which charset encoding are you saving (from your editor) you Java source?
2) Which charset encoding the java compiler assumes?
3) Which charset is your console?
4) Are you using some terminal with translation?
5) Does your console font include that particular character?
For getting issues 1-2 right, you should use UTF-8 for both (editor and javac settings), or more robust, specifify the Unicode char with escaped pure ascii text (Frakcool answer).
For issue 3, try -Dfile.encoding=UTF-8 or see this answer. Issues 4-5 are outside your Java program scope. If you are unsure, just redirect the ouput to a file, and look at it with a Hex editor.
A: When you save the java file, make sure it is saved in the same Charset as the one it is open.
In my Eclipse, when I save a file with special chars (such as \u2260) it asks me what charset I want to use.
Open your file in the terminal and inspect the content of the file.
Make sure it is the same char as the one in the editor you are using.
A: It seems that after Eclipse asked me if I want to change to UTF-8, it worked, only after I posted this.
Sorry for wasting your time
| |
doc_23526904
|
I have tried it with IronPython 2.7 and 2.6.10920
ExampleCode:
DynamicObject:
class ExampleDynamicObject: DynamicObject {
public override bool TryGetMember(GetMemberBinder binder,
out object result) {
result = "TryGetMember";
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder,
object[] args,
out object result) {
result = "TryInvokeMember";
return true;
}
}
calling Mathode
static void Main(string[] args) {
dynamic example = new ExampleDynamicObject();
var program = @"test = example.Call2(2)";
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("example", example);
var source = engine.CreateScriptSourceFromString(program,
SourceCodeKind.Statements);
source.Execute(scope);
Console.ReadKey();
}
This calls the TryGetMember method and then throws a Microsoft.Scripting.ArgumentTypeException "str is not callable"
This is thrown when u code something like 'test'(1)
So it seems that Python doesn't get that this is a Function call and instead just calls a Property.
But when i try to call it from C#
Console.WriteLine(example.Call);
Console.WriteLine("----------------------------");
Console.WriteLine(example.Call(1));
This will work:
TryGetMember
-------------------
TryInvokeMember
Has anyone a suggestion how to fix this?
Solution: (edit: calledMethodeName has to be a List, otherwise nested methods wouldn't work)
So thanks to Jeff.
When i design the Dynamic like that:
List<string> calledMethodeNames = new List<string>();
public override bool TryGetMember(GetMemberBinder binder,
out object result)
{
calledMethodeNames.Add(binder.Name);
result = this;
return true;
}
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
//calledMethodeNames last Element has stored the Name of the called methode (remeber to remove it)
result = "TryInvoke";
return true;
}
everything is working fine.
The clue is to return the Object itself as Member, than the object is callable and python calls the TryInvoke (not TryInvokeMember)
But TryInvoke ist called because after returning the object, the object itself is called. So InvokeBinder dont knows the Name of the called methode. So i store it into a variable.
A: That's the expected behaviour. IronPython uses TryGetMember followed by TryInvoke since the Python language has no concept of invoking a member: Python method calls are always an attribute lookup followed by a call.
The error you're getting is because you're setting result to a string (type str) and strings are not callable. You'll have to set result to either another dynamic object that implements TryInvoke or a delegate.
A: Based on the Python exception (str is not callable) it looks like IronPython first calls TryGetMember and since that function returns true it will use that object.
The TryGetMember/TryInvokeMember should only return true if they succeeded. For example that means TryGetMember should return true if and only if there actually is a member that matches the binder parameter.
Update: in C# Call(2) is always a method call (I can't think of anything else it could be, please let me know if I'm wrong), so the C# compiler will use TryInvokeMethod. In Python however any object is callable if it has a __call__ method, so Call(2) could either mean execute the method Call or get the member Call and execute __call__ on it.
| |
doc_23526905
|
I have tried the below mentioned code but nothing comes up.
Sub Copy_Files_Dates()
'This example copy all files between certain dates from FromPath to ToPath.
'You can also use this to copy the files from the last ? days
'If Fdate >= Date - 30 Then
'Note: If the files in ToPath already exist it will overwrite
'existing files in this folder
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim Filename As String
Dim FileInFromFolder As Object
FromPath = "K:\CIU\Data\FRC\monthly_checks*" & "*.csv*" '<< Change
ToPath = "C:\Users\WZHKLXH\Desktop\reporting" '<< Change
If Right(FromPath, 1) <> "\" Then
FromPath = FromPath & "\"
End If
If Right(ToPath, 1) <> "\" Then
ToPath = ToPath & "\"
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
If FSO.FolderExists(ToPath) = False Then
MsgBox ToPath & " doesn't exist"
Exit Sub
End If
For Each FileInFromFolder In FSO.getfolder(FromPath).Files
Filename = "monthly_checks*" & ".csv" ' or "dd.mm.yy")
'Copy files from 1-Aug-2020 to 20-Dec-2020
If Fdate >= DateSerial(2020, 7, 1) And Fdate <= DateSerial(2020, 12, 20) Then
FileInFromFolder.Copy ToPath
End If
Next FileInFromFolder
MsgBox "You can find the files from " & FromPath & " in " & ToPath
End Sub
| |
doc_23526906
|
gst-launch-1.0.exe -vv udpsrc port=5000 ! application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96 ! rtph264depay ! decodebin ! videoconvert ! video/x-raw,format=BGR ! videoconvert ! appsink name=sink
and it works fine.
now I am trying to add a recording using tee.
I tried :
gst-launch-1.0.exe -vv udpsrc port=5000 ! tee name=t t. ! application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96 ! queue ! rtph264depay ! decodebin ! videoconvert ! appsink ! t. ! application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96 ! queue ! rtph264depay ! h264parse ! mp4mux ! filesink location=test.mp4
for example but I get this error:
WARNING: erroneous pipeline: syntax error
I don't get how to use the tee.
each parts work fine alone, but when I am using the tee it doesn't work.
what is the correct syntax ?
(in my code instead of using gstlaunch-1.0.exe i am using gst_parse_launch)
A: In your pipe there is a ! between appsink and t (tee) elements. This connects the them. You want the branches to be separate.
gst-launch-1.0.exe -vv udpsrc port=5000 ! tee name=t t. ! application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96 ! queue ! rtph264depay ! decodebin ! videoconvert ! appsink t. ! application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96 ! queue ! rtph264depay ! h264parse ! mp4mux ! filesink location=test.mp4
A small note: Adding caps before tee would be more practical, so that you wouldn't need to write it twice.
gst-launch-1.0 -vv udpsrc port=5000 ! application/x-rtp,media=video,clock-rate=90000,encoding-name=H264,payload=96 ! tee name=t t. ! queue ! rtph264depay ! decodebin ! videoconvert ! appsink t. ! queue ! rtph264depay ! h264parse ! mp4mux ! filesink location=test.mp4
| |
doc_23526907
|
Specifically, after firing the crawl and index to Solr 4.5 then validating the results on the front-end with AJAX Solr, the search results page lists results/pages that are both 'www' and '' urls such as:
www.mywebsite.com
mywebsite.com
www.mywebsite.com/page1.html
mywebsite.com/page1.html
My understanding is that the url filtering aka regex-urlfilter.txt needs modification. Are there any regex/nutch experts that could suggest a solution?
Here is the code on pastebin.
A: There are at least a couple solutions.
1.) urlfilter-regex plugin
If you don't want to crawl the non-www pages at all, or else filter them at a later stage such as at index time, that is what the urlfilter-regex plugin is for. It lets you mark any URLs matching the regex patterns starting with "+" to be crawled. Anything that does not match a regex prefixed with a "+" will not be crawled. Additionally in case you want to specify a general pattern but exclude certain URLs, you can use a "-" prefix to specify URLs to subsequently exclude.
In your case you would use a rule like:
+^(https?://)?www\.
This will match anything that starts with:
https://www.
http://www.
www.
and therefore will only allow such URLs to be crawled.
Based on the fact that the URLs listed were already not being excluded given your regex-urlfilter, it means either the plugin wasn't turned on in your nutch-site.xml, or else it is not pointed at that file.
In nutch-site.xml you have to specify regex-urlfilter in the list of plugins, e.g.:
<property>
<name>plugin.includes</name>
<value>protocol-httpclient|urlfilter-regex|parse-(html|tika)|index-basic|query-(basic|site|url)|response-(json|xml)|urlnormalizer-(pass|regex|basic)</value>
</property>
Additionally check that the property specifying which file to use is not over-written in nutch-site.xml and is correct in nutch-default.xml. It should be:
<property>
<name>urlfilter.regex.file</name>
<value>regex-urlfilter.txt</value>
<description>Name of file on CLASSPATH containing regular expressions
used by urlfilter-regex (RegexURLFilter) plugin.</description>
</property>
and regex-urlfilter.txt should be in the conf directory for nutch.
There is also the option to only perform the filtering at different steps, e.g., index-time, if you only want to filter than.
2.) solrdedup command
If the URLs point to the exact same page, which I am guessing is the case here, they can be removed by running the nutch command to delete duplicates after crawling:
http://wiki.apache.org/nutch/bin/nutch%20solrdedup
This will use the digest values computed from the text of each indexed page to find any pages that were the same and delete all but one.
However you would have to modify the plugin to change which duplicate is kept if you want to specifically keep the "www" ones.
3.) Write a custom indexing filter plugin
You can write a plugin that reads the URL field of a nutch document and converts it in any way you want before indexing. This would give you more flexible than using an existing plugin like urlnormalize-regex.
It is actually very easy to make plugins and add them to Nutch, which is one of the great things about it. As a starting point you can copy and look at one of the other plugins including with nutch that implement IndexingFilter, such as the index-basic plugin.
You can also find a lot of examples:
http://wiki.apache.org/nutch/WritingPluginExample
http://sujitpal.blogspot.com/2009/07/nutch-custom-plugin-to-parse-and-add.html
| |
doc_23526908
|
He developped an app to permit some people to ask for changes to a firewall rules
When tou ask a change, you can select/fill:
firewall name (correspond to firewall interface)
Port
Source address
destination address
Service type (TCP/UDP/ICMP)
There are 2 tables in database:
Rule FW
---------- ---------
ID ID
Fw_Id Name
idrule Description
Port ----------
Source Address
Destination Adress
Service Type
----------
there's only 1 firewall/rule and 1 rule/firewall
my problem comes when i try to save the form, doctrine tries to save all the firewall informations not only the id and tells there's a unique key violation.
i searched but can't figure out what's wrong
the Rule Entity:
<?php
namespace FWBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Rule
*
* @ORM\Table(name="rule", uniqueConstraints={@ORM\UniqueConstraint(name="unique_fw_id", columns={"fw_id", "idrule"})})
* @ORM\Entity(repositoryClass="FwBundle\Repository\ruleRepository")
* @UniqueEntity(fields={"fw","idrule"}, message="Rule already exists")
*/
class Rule
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToOne(targetEntity="FwBundle\Entity\fw")
* @ORM\JoinColumn(name="fw_id",referencedColumnName="id")
* @Assert\Valid()
*/
private $fw;
/**
* @var int
*
* @ORM\Column(name="idrule", type="integer")
*/
private $idrule;
The FW Entity:
<?php
namespace FWBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* fw
*
* @ORM\Table(name="fw")
* @ORM\Entity(repositoryClass="FWBundle\Repository\FwRepository")
* @UniqueEntity(fields="name", message="Firewall already exists.")
*/
class Fw
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, unique=true)
*/
private $name;
The RuleController:
public function AddAction($id,Request $request)
{
$namespace = 'FwBundle';
$em = thiss->getDoctrine()->getManager();
$repositoryRule = $em->getRepository($namespace.':Rule');
$repositoryFw = $em->getRepository($namespace.':Fw');
$rule = new rule();
$form = $this->createForm(RuleType::class, $rule,array('fw'=>$id));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$rule = $form->getData();
$em->persist($rule);
$em->flush();
}
}
A: Rule can only be linked to one Firewall and one Firewall can be linked to a one Rule. What you are trying to do is linking many Rules to a single Firewall.
You should probably consider changing OneToOne relationship to ManyToOne like that a Firewall could have many Rules and the error should disappear ( you have to update your database schema before of course)
If you are sure that OneToOne is the one you want you should not create a new Rule in your form if the Firewall already have one.
Your code should be similar to this :
public function AddAction($id,Request $request)
{
$namespace = 'FwBundle';
$em = thiss->getDoctrine()->getManager();
$repositoryRule = $em->getRepository($namespace.':Rule');
$repositoryFw = $em->getRepository($namespace.':Fw');
$rule = new rule(); // remove this line and change it with the two lines below
$fw = $repositoryFw->find($id); // assuming that id is the id of firewall
$rule = $fw->getRule() ? : new Rule(); // if Firewall has a rule entity then take it otherwise create a new one.
$form = $this->createForm(RuleType::class, $rule,array('fw'=>$id));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$rule = $form->getData();
$em->persist($rule);
$em->flush();
}
}
| |
doc_23526909
| ||
doc_23526910
|
numFolds int 1 The number of folds to use for cross-validation.
startFold int 1 The starting fold to run.
numFoldsToRun int 1 The number of folds to run.
which I think should be used for cross validation. But I don't think they actually work. Setting numFolds to 1 or 10 doesn't change the running time for training at all. And strangely, using numFoldsToRun gives the following warning:
Unknown property: |numFoldsToRun|
A: You're right. These options haven't been implemented. If you want to run cross-validation experiments, you'll have to do it completely manually by preparing the data sets yourself. (Sorry!)
| |
doc_23526911
|
private String myName;
private int myAge;
private String myHeritage;
HelloStack(String myName, int myAge, String myHeritage){
this.myName = myName;
this.myAge = myAge;
this.myHeritage = myHeritage;
}
Then in my main() I create an object:
HelloStack hiGuys = new HelloStack("joseph", 89, "indian");
If my understanding is correct on the role of parameters here, I'm passing the values from hiGuys into the constructor Hellostack, and then they're actually initialized in the constructor when the compiler runs through?
A: No. First, you create the HelloStack object:
new HelloStack("joseph", 89, "indian");
Then a few things happen with object loading and instantiation that aren't relevant. The next thing is that the thread enters the constructor, calls an implicit super() constructor, and then sets the fields one at a time:
this.myName = myName;
this.myAge = myAge;
this.myHeritage = myHeritage;
Then the constructor "returns" the new object. That object is assigned to your hiGuys variable.
HelloStack hiGuys =
So now hiGuys has a single value - that new object.
| |
doc_23526912
|
f<-function(a=1,b=T,c) {}
formals(f) returns a pairlist with a "symbol" type values. So, i cannot just attach(as.list(formals(f)))...
A: Try this:
ff <- f
body(ff) <- quote(environment())
Now this will put them in the global environment:
list2env(as.list(ff()), .GlobalEnv)
or this will attach them to the search path:
attach(ff())
Note 1
a and b are normal variables but c is represented by a missing value so although it will be in the global environment or search path you can't print it; however, you can query whether or not it is such a variable like this:
inherits(try(c, silent = TRUE), "try-error")
## [1] TRUE
That expression will be FALSE for variables having a value.
Note 2
To only copy only the arguments having defaults to the global environment:
ff <- f
body(ff) <- quote({
L <- as.list(environment())
is_missing <- sapply(names(L), function(x) {
x <- as.list(ff)[[x]]
missing(x)
})
L[! is_missing]
})
list2env(ff(), .GlobalEnv)
or to attach them replace the last line with:
attach(ff())
| |
doc_23526913
|
I tried to map a timestamp column [ varbinary (8)] with byte array in my POJO. I received the following error:
JZ006: Caught IOException: java.io.IOException: JZ0SM: Unsupported SQL type 1111" after trying BINARY and byte[] for jdbcType and javaType respectively in the parametermap.
What would be the appropriate jdbcType and javaType to map this field through ibatis parametermap to a POJO?
A: For fixed length columns, use fixed length datatypes. Use BINARY(8).
It works for mapping Sybase TIMESTAMP columns onto other client software (I do not have your exact set).
| |
doc_23526914
|
A: Well that's just about flexibility, using a Resource will provide you a more generic object which will fit most of your need for common services while _init methods are likely to be specific and short.
Resources allows you to automatically load config object from the configuration file, while _init methods will ask you to do it manually.
There is no real difference except the way you work with.
*
*_init:
*
*simple case
*really specific
*maybe quicker
*
*resources:
*
*reusable
*allow different configuration format (ini, php, xml)
*maybe slower
Note: _init method with the same names as native resoures will overwrite current configuration.
| |
doc_23526915
|
Since febuary I've run a php5/mysql (maria DB)/apache2 server for some personal website.
But since yesterday, at 7 o'clock the mysql server doesn't work.
I connect to my server and type "mysql": Mysql command not found
I go on aptitude and I see the mariaDB is not installed !
Make a apt-get update
and reinstall mariaDB.
All is fine and work.
But the morning, I see I have the same problem. At 7 o'clock the mysql server (the mariaDB) is not installed. Type mysql return Mysql command not found.
Go to aptitude and unable to install mariaDB.
To install it I have to apt-get update then install mariaDB and all work fine..
But I think tomorrow at 7 o'clock the mysql server go out...
Any ideas?
thanks!
ps: sorry I'm not at home and I have not the precise time when the mysql is deleted and not all the correct error.. But if you have a similar problem plz help me !
Edit1:
My /var/log/dpkg.log
2015-04-21 04:17:48 startup packages remove
2015-04-21 04:17:48 status installed mariadb-server:all 5.5.42+maria-1~wheezy
2015-04-21 04:17:48 remove mariadb-server:all 5.5.42+maria-1~wheezy <none>
2015-04-21 04:17:48 status half-configured mariadb-server:all 5.5.42+maria-1~wheezy
2015-04-21 04:17:48 status half-installed mariadb-server:all 5.5.42+maria-1~wheezy
2015-04-21 04:17:48 status config-files mariadb-server:all 5.5.42+maria-1~wheezy
2015-04-21 04:17:48 status config-files mariadb-server:all 5.5.42+maria-1~wheezy
2015-04-21 04:17:48 status config-files mariadb-server:all 5.5.42+maria-1~wheezy
2015-04-21 04:17:48 status not-installed mariadb-server:all <none>
2015-04-21 04:17:48 status installed mariadb-server-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:48 remove mariadb-server-5.5:amd64 5.5.42+maria-1~wheezy <none>
2015-04-21 04:17:48 status half-configured mariadb-server-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:49 status half-installed mariadb-server-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 status triggers-pending man-db:amd64 2.6.2-1
2015-04-21 04:17:50 status half-installed mariadb-server-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 status config-files mariadb-server-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 status config-files mariadb-server-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 status installed mariadb-client-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 remove mariadb-client-5.5:amd64 5.5.42+maria-1~wheezy <none>
2015-04-21 04:17:50 status half-configured mariadb-client-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 status half-installed mariadb-client-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 status half-installed mariadb-client-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 status config-files mariadb-client-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 status config-files mariadb-client-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 status installed mariadb-client-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:50 remove mariadb-client-core-5.5:amd64 5.5.42+maria-1~wheezy <none>
2015-04-21 04:17:50 status half-configured mariadb-client-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status half-installed mariadb-client-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status half-installed mariadb-client-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status config-files mariadb-client-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status config-files mariadb-client-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status config-files mariadb-client-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status not-installed mariadb-client-core-5.5:amd64 <none>
2015-04-21 04:17:51 status installed mariadb-server-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 remove mariadb-server-core-5.5:amd64 5.5.42+maria-1~wheezy <none>
2015-04-21 04:17:51 status half-configured mariadb-server-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status half-installed mariadb-server-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status half-installed mariadb-server-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status config-files mariadb-server-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status config-files mariadb-server-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status config-files mariadb-server-core-5.5:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status not-installed mariadb-server-core-5.5:amd64 <none>
2015-04-21 04:17:51 status installed libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:51 status installed libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 status installed libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 status installed libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 status installed libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 status installed libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 status installed libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 status installed libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 remove libmariadbclient18:amd64 5.5.42+maria-1~wheezy <none>
2015-04-21 04:17:52 status half-configured libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 status half-installed libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 status config-files libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 status config-files libmariadbclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:52 trigproc man-db:amd64 2.6.2-1 <none>
2015-04-21 04:17:52 status half-configured man-db:amd64 2.6.2-1
2015-04-21 04:17:53 status installed man-db:amd64 2.6.2-1
2015-04-21 04:17:53 startup archives unpack
2015-04-21 04:17:53 upgrade libmysqlclient18:amd64 5.5.42+maria-1~wheezy 5.5.43-0+deb7u1
2015-04-21 04:17:53 status half-configured libmysqlclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:53 status unpacked libmysqlclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:53 status half-installed libmysqlclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:53 status half-installed libmysqlclient18:amd64 5.5.42+maria-1~wheezy
2015-04-21 04:17:54 status unpacked libmysqlclient18:amd64 5.5.43-0+deb7u1
2015-04-21 04:17:54 status unpacked libmysqlclient18:amd64 5.5.43-0+deb7u1
2015-04-21 04:17:54 startup packages configure
2015-04-21 04:17:54 configure libmysqlclient18:amd64 5.5.43-0+deb7u1 <none>
2015-04-21 04:17:54 status unpacked libmysqlclient18:amd64 5.5.43-0+deb7u1
2015-04-21 04:17:54 status half-configured libmysqlclient18:amd64 5.5.43-0+deb7u1
2015-04-21 04:17:54 status installed libmysqlclient18:amd64 5.5.43-0+deb7u1
There are a few cron on the server but only for refreshing some data.
But this morning when I try to reinstall mariaDB Aptitude give me some error (don't remember the exact term) and it was unable to install mariaDB.
For install I have to apt-get update and then go to aptitude and select package. it return me some error with 3 options (Examine, Valid and other don't remember option:( )
If I don't find a solution this night, I screenshot tomorrow morning if mariaDB go out..
But if anyone have a solution I'll take it !
thanks !
Edit2
some screenshot take this morning:
Before execute apt-get update:
http://i.imgur.com/adoMWTj.png
We show the package have no version installed et no version available
After execute apt-get update:
8 Screenshots here
We show some red error, with suggest. The suggest 6 keep make nothing if I apply it.
The suggest 1 downgrade, dowgrade libmysqlclient18 and install mariaDB..
But dpkg remove mariaDB all the morning...
Please help me :)
A: Fixed, my problem.
I follow this tutorial for setting up my server and he force the security installation without take the mariaDB repo.
| |
doc_23526916
|
A: This is what source.android.com says about this:
Similar to preloaded classes in the zygote, ART attempts to pre-initialize a set of classes at compile time. This creates a ‘boot.art’ file that comprises an image of the compacted heap of pre-initialized classes and related objects. This file is mapped into memory upon zygote startup. While this consumes additional storage (typically 10MB), it speeds zygote startup and creates opportunities for the system to swap out some preloaded classes under memory pressure. This also contributes to improved low-RAM performance for ART, since in Dalvik much of this class information would have been stored in dirty pages in the linear alloc space.
Link here
| |
doc_23526917
|
please if there is a documentation or link that you can bring me where i can start would be great .
thanks in advance
A: i have just found the documentation, thanks a lot. Here it is if it can help anyone: http://developer.android.com/intl/es/google/play/billing/index.html
| |
doc_23526918
|
From main.py
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
Window.clearcolor = 255 / 255, 255 / 255, 255 / 255, 1
Window.size = 414, 736
sm = ScreenManager()
class PulseWelcome(Screen):
pass
class PulseWelcomeCanvas(Widget):
pass
class PulseLogin(Screen):
class PulseLoginCanvas(Widget):
pass
class WindowManager(ScreenManager):
pass
sm.add_widget(PulseWelcome(name = 'welcome'))
sm.add_widget(PulseLogin(name = 'login'))
class PulseApp(App):
def build(self):
return PulseWelcome()
if __name__ == '__main__':
PulseApp().run()
From Pulse.kv
#:kivy 2.1.0
WindowManager:
PulseWelcome:
PulseLogin:
<PulseWelcome>:
id: welcome
PulseWelcomeCanvas:
Label:
font_size: 30
font_name: 'assets/fonts/tommy.ttf'
center_x: root.width / 2
center_y: root.height / 2
text: "Welcome to Pulse!"
color: 0, 0, 0, 1
Button:
background_normal: 'assets/images/next_purple_normal.png'
background_down: 'assets/images/next_purple_down.png'
border: 0, 0, 0, 0
center_x: root.width / 2
center_y: 90
height: 40
width: 100
on_press:
root.manager.transition.direction = 'left'
root.manager.current = 'login'
<PulseLogin>:
id: login
PulseLoginCanvas:
Label:
font_size: 30
font_name: 'assets/fonts/tommy.ttf'
text: 'Sign In or Sign Up'
color: 0, 0, 0, 1
center_x: root.width / 2
center_y: root.height / 2
My app runs as it should when the program is started, however, when I click on my button in order to change screens I am presented with this error:
File "C:\Users\Nitro\Documents\Pulse\pulse.kv", line 30, in <module>
root.manager.transition.direction = 'left'
AttributeError: 'NoneType' object has no attribute 'transition'
I have tried a variety of solutions with no progress. My guess is that because I am trying to switch screens from a widget inside my screen class I am given the earlier discussed error. I originally decided to put a widget inside each screen class to organize elements because when I had tried to organize elements in the .kv file for the screen class independently (PulseWelcome, etc.) I had gui issues.
I also had tried defining a function in the screen class that could be activated through the contained widget. After trying that I was given this error:
kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget.
Not sure if anyone out there knows what may be causing the issue and how to fix it but if anyone has any sort of input for any of the issues previously mentioned all help is greatly appreciated.
A: You have not initialized the screenmanager you returning the screen and not the screenmanager
main.py:
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
Window.clearcolor = 255 / 255, 255 / 255, 255 / 255, 1
Window.size = 414, 736
class PulseWelcome(Screen):
pass
class PulseWelcomeCanvas(Widget):
pass
class PulseLogin(Screen):
class PulseLoginCanvas(Widget):
pass
class WindowManager(ScreenManager):
pass
class PulseApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(PulseWelcome(name='welcome'))
sm.add_widget(PulseLogin(name='login'))
return sm
if __name__ == '__main__':
PulseApp().run()
defining the build function like this should do the trick.
.kv:
<PulseWelcome>:
id: welcome
PulseWelcomeCanvas:
Label:
font_size: 30
font_name: 'assets/fonts/tommy.ttf'
center_x: root.width / 2
center_y: root.height / 2
text: "Welcome to Pulse!"
color: 0, 0, 0, 1
Button:
background_normal: 'assets/images/next_purple_normal.png'
background_down: 'assets/images/next_purple_down.png'
border: 0, 0, 0, 0
center_x: root.width / 2
center_y: 90
height: 40
width: 100
on_press:
root.manager.transition.direction = 'left'
root.manager.current = 'login'
<PulseLogin>:
id: login
PulseLoginCanvas:
Label:
font_size: 30
font_name: 'assets/fonts/tommy.ttf'
text: 'Sign In or Sign Up'
color: 0, 0, 0, 1
center_x: root.width / 2
center_y: root.height / 2
I have also removed the screenmanager from the kv file as that wouldn't function when creating the screenmanger like I have done here. Otherwise you would have to create the build function like this
build:
def build:
returm WindowManager()
I have run in to some trouble with doing the build function like that so for now I would do it the way I first showed you
Hope this helps
| |
doc_23526919
|
I've found 2 similar functions
currentAuthenticatedUser() and currentUserPoolUser().
They have the same description, parameters, and returns.
I want to know why they separated.
[reference]
https://aws-amplify.github.io/amplify-js/api/classes/authclass.html#currentauthenticateduser
https://aws-amplify.github.io/amplify-js/api/classes/authclass.html#currentuserpooluser
A: I believe user pool users are those that are from Cognito, whereas an authenticated user is one that come from an identity pool (from a federated identity).
See: https://aws.amazon.com/premiumsupport/knowledge-center/cognito-user-pools-identity-pools/
A: From the code, it looks like currentAuthenticatedUser checks for federation info. However, if it doesn't find federation info, it just calls currentUserPoolUser. So I'd say call currentUserPoolUser if you know you're never going to be using federated logins, but you should probably call currentAuthenticatedUser if there's a chance you might.
A: according to amplify auth docs, both result in "A promise resolves to current authenticated CognitoUser if success"
| |
doc_23526920
|
For example, the method with input "loooooveee" should return 6 (4 times 'o', 2 times 'e').
I'm trying to implement string level functions and I can do it this way but, is there an easy way to do this? Regex, or some other sort of things?
A: You could use a regular expression if you want:
import re
rx = re.compile(r'(\w)\1+')
repeating = sum(x[1] - x[0] - 1
for m in rx.finditer("loooooveee")
for x in [m.span()])
print(repeating)
This correctly yields 6 and makes use of the .span() function.
The expression is
(\w)\1+
which captures a word character (one of a-zA-Z0-9_) and tries to repeat it as often as possible.
See a demo on regex101.com for the repeating pattern.
If you want to match any character (that is, not only word characters), change your expression to:
(.)\1+
See another demo on regex101.com.
A: Original question: order of repetition does not matter
You can subtract the number of unique letters by the number of total letters. set applied to a string will return a unique collection of letters.
x = "loooooveee"
res = len(x) - len(set(x)) # 6
Or you can use collections.Counter, subtract 1 from each value, then sum:
from collections import Counter
c = Counter("loooooveee")
res = sum(i-1 for i in c.values()) # 6
New question: repetitions must be sequential
You can use itertools.groupby to group sequential identical characters:
from itertools import groupby
g = groupby("aooooaooaoo")
res = sum(sum(1 for _ in j) - 1 for i, j in g) # 5
To avoid the nested sum calls, you can use itertools.islice:
from itertools import groupby, islice
g = groupby("aooooaooaoo")
res = sum(1 for _, j in g for _ in islice(j, 1, None)) # 5
A: try this:
word=input('something:')
sum = 0
chars=set(list(word)) #get the set of unique characters
for item in chars: #iterate over the set and output the count for each item
if word.count(char)>1:
sum+=word.count(char)
print('{}|{}'.format(item,str(word.count(char)))
print('Total:'+str(sum))
EDIT:
added total count of repetitions
A: Since it doesn't matter where the repetition is occurring or which characters are being repeated, you can make use of the set data structure provided in Python. It will discard the duplicate occurrences of any character or an object.
Therefore, the solution would look something like this:
def measure_normalized_emphasis(text):
return len(text) - len(set(text))
This will give you the exact result.
Also, make sure to look out for some edge cases, which you should as it is a good practice.
A: I think your code is comparing the wrong things
You start by finding the last character:
char = text[-1]
Then you compare this to itself:
for i in range(1, len(text)):
if text[-i] == char: #<-- surely this is test[-1] to begin with?
Why not just run through the characters:
def measure_normalized_emphasis(text):
char = text[0]
emphasis_size = 0
for i in range(1, len(text)):
if text[i] == char:
emphasis_size += 1
else:
char = text[i]
return emphasis_size
This seems to work.
| |
doc_23526921
|
I Need some thing like this.if i have url :
http://tageto.pnf-sites.info/developer/headcategory_controller/head_category/Agriculture
than it must be replaced into
http://tageto.pnf-sites.info/developer/Agriculture
and if i have url like this
http://tageto.pnf-sites.info/developer/headcategory_controller/sub_category/Rice
than it must be replaced into
http://tageto.pnf-sites.info/developer/Agriculture/Rice
Can anybody solve my this issue? Please reply rapidly.
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(developer)/[^/]+/[^/]+/(.+)$ /$1/$2 [NC,L,R=302]
</IfModule>
By This -> ERROR 404 - Not Found!
A: Try this rule in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteRule ^(developer)/[^/]+/[^/]+/(.+)$ /$1/$2 [NC,L,R=302]
A: You can try the below in htaccess
RewriteCond %{HTTPS} on
RewriteRule ^developer/headcategory_controller/sub_category/Rice http://%{SERVER_NAME}%{REQUEST_URI} [R,L]
You can try this rout.php
$route['developer/Agriculture/(:any)'] = 'developer/headcategory_controller/sub_category/$1';
| |
doc_23526922
|
I'm using the following code, basically taken word for word from their official example program:
var access_token;
app.get('/callback', function(req, res) {
// your application requests refresh and access tokens
// after checking the state parameter
var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
if (state === null || state !== storedState) {
res.redirect('/#' +
querystring.stringify({
error: 'state_mismatch'
}));
} else {
res.clearCookie(stateKey);
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
access_token = body.access_token,
refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
});
// we can also pass the token to the browser to make requests from there
res.redirect('/#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
} else {
res.redirect('/#' +
querystring.stringify({
error: 'invalid_token'
}));
}
});
}
So I have var access_token, and then I try to set access_token equal to body.access_token, which I'm assuming should be the value of the access token. However, when I run a console.log("My access token: "+access_token), it says my access token is undefined! The reason why this is so confusing for me is that the corresponding HTML file, where it seems to send the access token, the token shows up perfectly fine!
Does anybody know what I might be doing wrong here? I feel like I just don't grasp the big picture well enough right now.
A: The response body might be plain text and would need to be parsed. Try doing
body = JSON.parse(body);
before setting access_token and refresh_token
| |
doc_23526923
|
However in none of the .Net SHA256 classes (eg System.Security.Cryptography.SHA256Managed) can I find a reference to a Key property or anything like that.
Does anyone know how to do this in .Net? (This ideally has to be .Net3.5, which the application targets.)
TIA
A: You've been asked to compute the Hash-based Message Authentication Code (HMAC) with SHA256. For this you will want to use the HMACSHA256 class - the documentation also includes an example of how to implement this.
A: There is no key for SHA256. It is hash function and returns the same value each time for the same input. This is not encryption with key.
| |
doc_23526924
|
<div style="background: url('images/slider/slider1.jpg') no-repeat fixed center; height: 100vh;">
I have this piece, I have tried to make it become
<div style={{"background: url('images/slider/slider1.jpg') no-repeat fixed center; height: 100vh"}}>
And I tried to change it to <div style={{background: url('images/slider/slider1.jpg') no-repeat fixed center; height: 100vh}}>
Or else I tried it to
<div style={{"background: url('images/slider/slider1.jpg') no-repeat fixed center, height: '100'vh"}}>
It won't work either, I need some little guidance and help, thank you!
A: You have to write it like that :
{ background: "all your properties", height: "100vh" }
please have a look at React documentation: https://reactjs.org/docs/dom-elements.html#style
| |
doc_23526925
|
The table planes contains many columns out of which dtd(column containing many days of type varchar(50)) .
One record(in dtd) is Monday, Tuesday
The user enters the date 2018-12-03 which is a Monday.
My problem is how do I extract only the record which has Monday?(like the monday,Tuesday one)??
I tried select.....where instr(day(2018-12-03),dtd)<>0 but I realised that instr gives 0 in 2 cases
1. the character(s) is not present in the record or
2.occurence is at the beginning.
Like instr(h,hello) and instr(a,hello) gives 0.
Please help
A: I suggest that you use the LIKE operator.
For more info about it please check this link: SQL Like Operator
To solve your problem, you can try the following:
SELECT ...
WHERE dtd LIKE CONCAT('%', day(2018-12-03), '%');
In this case, you will get all the rows of the table, where the value of the field dtd contains the value of day(2018-12-03).
Hope this helps!
| |
doc_23526926
|
an example code is: <a id="foo" href="bar.php" ><span>BAR</span></a>
I hide the <span> and use the background image instead.
My Question Is:
Is this form of navigation good for SEO? Is hiding the <span> seen as spam by the search engines. Will search engines even pick up this form of menu??
Please Help
A: Many/most/(all?) search engines will not understand CSS to the degree that they know you're hiding the <span>. For those, you're fine.
For any that are bright enough to understand your CSS, they'll also understand the reasons why people do that, and will recognise what you're doing. So for those you're fine too.
Many questions like this one boil down to "Are search engines just clever enough to misunderstand what I'm doing?" And the answer is no, because it's not in their interests. As the author of a search engine, you wouldn't add support for noticing CSS-hiding without also adding reliable heuristics to tell the difference between its normal use and its abuse.
A: You may use text-indent css property for your <li> or <a> element. This way you won't have to hide it via css. So you'd have something like this
<ul>
<li><a id="foobar">foobar</a></li>
</ul>
Then you could have following css:
li a {
display: block;
text-indent: -1000px;
width: 20px;
height: 20px;
background: transparent url('/image/path.png') no-repeat;
}
A: If you are simply going to hide them using
display: none;
then you will want to check out the question Stack Overflow thinks is most related to yours: Google SEO and hidden elements.
Summary: Google ignores anything it can determine is invisible to humans.
| |
doc_23526927
|
My question is: Why isn't the classes compiled and not loadable? Maybe there's a missing configuration of the kompiler.
@BeforeEach
fun setup() {
val kotlinSource = SourceFile.kotlin(
"TestClass.kt", """
package test.pack
import yy.xxx.dsl.builder.annotation.DslBuilder
@DslBuilder
class TestClass {
}
"""
)
val compilation = KotlinCompilation().apply {
sources = listOf(kotlinSource)
symbolProcessorProviders = listOf(DslBuilderProcessorProvider())
//workingDir =
inheritClassPath = true
verbose = false
//messageOutputStream = System.out
kspIncremental = true
}
compilationResult = compilation.compile()
assertEquals(KotlinCompilation.ExitCode.OK, compilationResult.exitCode)
// The next line leads to java.lang.ClassNotFoundException
compilationResult.classLoader.loadClass("test.pack.TestClassDslBuilder")
}
A: I have the same issue.
Didn't fix it, but it seems to me, that problem is in path of generated file (which you wrote like string), like in google compile testing it was important to use StandardLocation.SOURCE_OUTPUT, when you try to find generatedFile().
But in my case, it doesn't generate anything - I mean generatedFiles.size() == 0 in KotlinCompilation.Result
A: This lib is not compatible with KSP fully yet. There is a hack to make it work with double compilation: https://github.com/tschuchortdev/kotlin-compile-testing/issues/72#issuecomment-744475289
fun compile(tempDir: File, compilation: KotlinCompilation): KotlinCompilation.Result {
val pass1 = compilation.compile()
require(pass1.exitCode == KotlinCompilation.ExitCode.OK) {
"Cannot do the 1st pass \n ${pass1.messages}"
}
val pass2 = KotlinCompilation().apply {
sources = compilation.kspGeneratedSourceFiles(tempDir) + compilation.sources
inheritClassPath = true
}.compile()
require(pass2.exitCode == KotlinCompilation.ExitCode.OK) {
"Cannot do the 2nd pass \n ${pass2.messages}"
}
return pass2
}
private fun KotlinCompilation.kspGeneratedSourceFiles(tempDir: File): List<SourceFile> =
kspGeneratedSources(tempDir)
.filter { it.isFile }
.map { SourceFile.fromPath(it.absoluteFile) }
.toList()
}
private fun kspGeneratedSources(tempDir: File): List<File> {
val kspWorkingDir = tempDir.resolve("ksp")
val kspGeneratedDir = kspWorkingDir.resolve("sources")
val kotlinGeneratedDir = kspGeneratedDir.resolve("kotlin")
val javaGeneratedDir = kspGeneratedDir.resolve("java")
return kotlinGeneratedDir.walkTopDown().toList() +
javaGeneratedDir.walkTopDown()
}
And I can confirm that it works. This is just an example. Depending on your output directory, you might want to tinker with the file paths a bit, of course. If it still doesn't work, make sure that the second KotlinCompilation() is right for your case.
| |
doc_23526928
|
like in the image
center parent of parent
A: You have to change things around a bit, you can't put a view relative to a parent's parent.
You need a RelativeLayout as the root layout, and then you place the blue line centered vertically. Then you would place the red LinearLayouts above and below the blue layout. Something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/blue_layout"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_centerVertical="true"
android:background="#ff0000ff" />
<LinearLayout
android:id="@+id/above"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/blue_layout"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="@+id/below"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/blue_layout"
android:orientation="vertical">
</LinearLayout>
</RelativeLayout>
| |
doc_23526929
|
It can be :
banana-split.taste
Or
banana.taste
What I want is everything after and before the point.
But if a hyphen happens to exist in the string before the point, I want the string in between the hyphen and the point
With my examples it would result like this :
Example 1
match[1] = banana
match[2] = split
match[3] = taste
Example 2
match[1] = banana
match[2] =
match[3] = taste
What I tried is using positive lookahead/behind but I feel I use it badly
(.+)(?<=\-)(.*?)?\.(.+)
With this I am able to get nicely the first example, but not the second
A: Use negated character classes and an optional group:
([^-]+)(?:-([^.]+))?\.(.+)
See the regex demo
Details:
*
*([^-]+) - Group 1: one or more chars other than - as many as possible
*(?:-([^.]+))? - an optional group matching 1 or 0 occurrences of:
*
*- - a hyphen
*([^.]+) - Group 2: one or more chars other than . as many as possible
*\. - a dot
*(.+) - any 1+ chars other than line break chars
A: There is nothing wrong with Wiktor's answer; I have a high regard for the quality of his answers.
Purely for educational purposes, I'd like to explain that preg_match() is not the only regex-based function to extract substrings from a string. Consider this one-liner:
Method:
var_export(preg_split('/[-\.]/',$str));
Inputs/Outputs:
$str='banana-split.taste'; // ['banana','split','taste']
$str='banana.taste'; // ['banana','taste']
Notice how preg_split() does not use capture groups (so no empty capture groups) and doesn't include the (often useless) fullstring match in its output.
I don't know the process that you are using, but if this simplifies your process, then I am glad that I chimed in.
| |
doc_23526930
|
I have a simple HTML template which has a form element 2 input boxes and dropdown list.
VIEW
<form class = 'form-class'
[formGroup] = form
(ngSubmit) = "onSubmit(form.value)"
>
<input type = 'text' name = 'firstName' placeholder="Enter First Name ..." formControlName="firstName">
<input type = 'text' name = 'lastName' placeholder="Enter Last Name ..." formControlName="lastName">
<span>{{ selectedLang }}</span>
<ul>
<li *ngFor = "let lang of languagesList" (click)="selectedLang = lang" > {{ lang }} </li>
</ul>
<input type="submit" name="Submit">
</form>
CONTROLLER
export class ModelDrivenFormsComponent implements OnInit {
form;
ngOnInit() {
this.form = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
selectedLang: new FormControl(this.selectedLang) // this doesn't work
});
}
languagesList = ['English', 'Hindi', 'Konkani'];
selectedLang = 'Select Now';
onSubmit = function (user) {
user.selectedLang = this.selectedLang; // <-- this is something i want to avoid
}
}
The Above is the model driven form. Similarly I have also tried using template driven form in the below way.
<form class = 'form-class'
#thisFormName = "ngForm"
(ngSubmit) = "saveData(thisFormName.value)"
>
<input type = 'text' name = 'firstName' placeholder="Enter First Name ..." ngModel>
<input type = 'text' name = 'lastName' placeholder="Enter Last Name ..." ngModel>
<span>{{ selectedLang }}</span>
<ul >
<li *ngFor = "let lang of languagesList" (click)="selectedLang = lang" > {{ lang }} </li>
</ul>
<input type="submit" name="Submit">
</form>
Is there a way to add ngModel (or something similar) to ul li so that the controller gets the selectedLang when the user sumbits the form?
Thanks in Advance.
A: If you want to make a dropdown, you should not use ul li.
In my mind, the best way is to use select with ngModel.
<select [(ngModel)]="selectedLang ">
<option *ngFor="let lang of languagesList" [ngValue]="lang ">{{lang }}</option>
</select>
If you want to use more detail in your dropdown, you can see these following components:
*
*Primeng
*Bootstrap
*Material
| |
doc_23526931
|
The way the audio is added is:
xtype: 'audio',
hidden: true,
url: '/audio/crash.mp3',
The correct audio-URL is added from store later.
I then have a button that finds the audio and sets:
audio.toggle()
Why is it not working when I add it to the homescreen? Is it a sencha or an ios7 problem?
A: For those who have the same problem: It didn't work with the xtype: audio. I don't know why, but i think it is a bug in ios7 or something. The sollution or "quickfix" i did was to add an audio-tag with javascript and just play that.
var a = new Audio("YOUR AUDIO URL"); a.play();
| |
doc_23526932
|
*
*the new view will be put on top of the stack?
*once the new view unwinds, the new view will be destroyed?
*if you unwind back to the initial, then all views will be destroyed except the initial view?
A: "Show" segue, new in iOS 8, is simply a shorthand for calling UIViewController's showViewController:sender:, which is documented here:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/showViewController:sender:
And, for UINavigationController, here: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UINavigationController_Class/#//apple_ref/occ/instm/UINavigationController/showViewController:sender:
As you can see simply by reading the docs, if the view controller in question is the child of a navigation controller, and we are not in a split view controller situation, this method is identical to calling pushViewController:animated: on the navigation controller. Thus, in such a situation, the "show" segue is identical to the "push" segue from previous iOS versions.
| |
doc_23526933
|
STANDARD_SIZE = 1760;
window.addEventListener('resize', function(event){
if(window.innerWidth < STANDARD_SIZE ){
$.post('/a', {size:'mobile'}, function(res){
document.open();
document.write(res);
document.close();
})}
else{
$.post('/a', {size:'window'}, function(res){
document.open();
document.write(res);
document.close();
})}});
Above is my code. Problem is when I resize my window, I need this code to active for last size, not the first size.
For example, I coded alert('mobile') and alert('window') to each if and else. When I resized width lower than 1760, it alert window 3 times and then alert mobile.
So I need that last 'mobile' to alert on first time, not last. Any idea?
And also is there more simple code than above code?
I am keep trying my code, above code does work when I resize above 1760.
But when I try to resize below 1760, It does not work.
(SOLVED) Above code does work. I was keep wondering why it work on window, but not mobile size. So I checked on server code(python). It was just word spelling error. Thanks for other answer below! Since there is know code error above, I will just leave for other who need help with resizing function.
A: Since there is no event for "resize finished" you can set a timeout so your code won't run unless enough time was passed since the last resize event.
STANDARD_SIZE = 1760;
var resizeTimer;
window.addEventListener('resize', function(event) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
if (window.innerWidth < STANDARD_SIZE) {
alert("mobile");
/*
$.post('/a', {
size: 'mobile'
}, function(res) {
document.open();
document.write(res);
document.close();
})
*/
} else {
alert("window");
/*
$.post('/a', {
size: 'window'
}, function(res) {
document.open();
document.write(res);
document.close();
})
*/
}
}, 250);
});
A: You can restrict to multiple call
STANDARD_SIZE = 1760;
var DEVICE = 'window';
window.addEventListener('resize', function(event){
if(window.innerWidth < STANDARD_SIZE && DEVICE != 'mobile' ){
DEVICE = 'mobile';
$.post('/a', {size:'mobile'}, function(res){
document.open();
document.write(res);
document.close();
})}
else if(DEVICE != 'window'){
DEVICE = 'window';
$.post('/a', {size:'window'}, function(res){
document.open();
document.write(res);
document.close();
})}});
A: I think you don't need to add new event listener for resize. Just do sample like below:
<body onresize="resizeHandler()">
then define your resizeHandler() function:
var STANDARD_SIZE = 1760;
var isWindow = true;
function resizeHandler() {
if (window.innerWidth < STANDARD_SIZE && isWindow) {
isWindow = false;
alert('Mobile');
} else if (!isWindow) {
isWindow = true;
alert('Window');
}
}
The function handler above is just a trick to deal with your problem.
| |
doc_23526934
|
var folderId = "'the-folder-id'";
drive.files.list({
q: folderId + " in parents", // to get all the files in the folder
fields: 'files(id)'
}, (err, res) => {
if (err) throw err;
const files = res.data.files;
files.map(file => {
drive.files.get({
fileId: file.id,
alt: 'media'
},
{ responseType: "stream" },
(err, { data }) => {
message.member.voiceChannel.join().then(connection => {
const dispatcher = connection.playStream(data); // doesn't wait for this to finish to play the next stream (song)
}).catch(err => console.log(err));
});
});
});
Note that I have a command to make the bot leave the channel, so it's normal that there isn't any voiceChannel.leave() in my code, as I don't want it to leave right after the songs have finished playing.
Any advice is welcome, thanks in advance!
A: *
*You want to play multiple MP3 files by downloading them from the specific folder in Google Drive.
*You have already been able to play the MP3 data at the voice channel and use Drive API.
*You want to achieve this using discord.js and googleapis with Node.js.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In this answer, the MP3 files downloaded by googleapis are converted to the stream and put to the voice channel with discord.js.
Modified script:
var folderId = "'the-folder-id'";
drive.files.list(
{
q: folderId + " in parents", // to get all the files in the folder
fields: "files(id)"
},
(err, res) => {
if (err) throw err;
const files = res.data.files;
Promise.all(
files.map(file => {
return new Promise((resolve, reject) => {
drive.files.get(
{
fileId: file.id,
alt: "media"
},
{ responseType: "stream" },
(err, { data }) => {
if (err) {
reject(err);
return;
}
let buf = [];
data.on("data", function(e) {
buf.push(e);
});
data.on("end", function() {
const buffer = Buffer.concat(buf);
resolve(buffer);
});
}
);
});
})
)
.then(e => {
const stream = require("stream");
let bufferStream = new stream.PassThrough();
bufferStream.end(Buffer.concat(e));
message.member.voiceChannel
.join()
.then(connection => {
const dispatcher = connection.playStream(bufferStream);
dispatcher.on("end", () => {
// do something
console.log("end");
});
})
.catch(e => console.log(e));
})
.catch(e => console.log(e));
}
);
*
*In this sample script, when all MP3 files were finished, end is shown in the console.
References:
*
*Promise.all()
*Class: stream.PassThrough
*Class Method: Buffer.concat(list[, totalLength])
If I misunderstood your question and this was not the direction you want, I apologize.
Edit:
In the following sample script, all files in the specific folder on Google Drive are downloaded every one file and that is played with the stream.
Sample script:
var folderId = "'the-folder-id'";
drive.files.list(
{
q: folderId + " in parents",
fields: "files(id,name)"
},
(err, res) => {
if (err) throw err;
const channel = message.member.voiceChannel;
channel
.join()
.then(connection => playFiles(drive, channel, connection, res.data.files))
.catch(e => console.log(e));
}
);
*
*The function of playFiles() is called from above script.
Function of playFiles()
function playFiles(drive, channel, connection, files) {
if (files.length == 0) {
channel.leave();
return;
}
drive.files.get(
{
fileId: files[0].id,
alt: "media"
},
{ responseType: "stream" },
(err, { data }) => {
if (err) throw new Error(err);
console.log(files[0]); // Here, you can see the current playing file at console.
connection
.playStream(data)
.on("end", () => {
files.shift();
playFiles(drive, channel, connection, files);
})
.on("error", err => console.log(err));
}
);
}
*
*In this case, channel.leave() is important. I confirmed that when this is not used, there are the cases that at the next play, the sound cannot be listened from 2nd file. Please be careful this.
| |
doc_23526935
|
Technically speaking, I know how to do that:
[{
$match: { 'domains.name': '<DOMAIN_HERE>' },
}, {
$lookup: {
from: 'campaigns',
localField: '_id',
foreignField: 'tenantId',
as: 'campaign',
pipeline: [{
$match: { slug: '<SLUG_HERE>' },
}],
},
}]
which returns:
{
_id: ObjectId('...'),
campaign: [{
_id: ObjectId('...'),
}],
}
But it feels very uncomfortable, because for one the campaign is returned as a field of tenant and for other the campaign is returned as a single item in an array. I know, I can process and better format the result programmatically afterwards. But is there any way to „hack“ the aggregation to achieve a result that looks more like this?
{
tenant: {
_id: ObjectId('...'),
},
campaign: {
_id: ObjectId('...'),
},
}
This is just a simplified example, in reality this aggregation query is a bit more complicated (across more collections, upon few of which I need to perform a very similar query), so it's not just about this one simple query. So the ability to return an aggregated document as a separate object, rather than an array field on parent document would be quite helpful - if not, the world won't fall apart :)
A: To all those whom it may concern...
Thanks to answers from some good samaritans here, I've figured it out as a combination of $addFields, $project and $unwind. Extending my original aggregation query, the final pipeline would look like this:
[{
$match: { 'domains.name': '<DOMAIN_HERE>' },
}, {
$addFields: { tenant: '$$ROOT' },
}, {
$project: { _id: 0, tenant: 1 },
}, {
$lookup: {
from: 'campaigns',
localField: 'tenant._id',
foreignField: 'tenantId',
as: 'campaign',
pipeline: [{
$match: { slug: '<SLUG_HERE>' },
}],
},
}, {
$unwind: {
path: '$campaign',
preserveNullAndEmptyArrays: true,
},
}]
Thanks for the help!
| |
doc_23526936
|
$host = "" ; <---- IP
$hGUI = GUICreate("Terminal Serveur", 952, 675, -1, -1, $WS_OVERLAPPEDWINDOW + $WS_CLIPSIBLINGS + $WS_CLIPCHILDREN)
$oRDP = ObjCreate("MsTscAx.MsTscAx.2")
$oRDP_Ctrl = GUICtrlCreateObj($oRDP, 64, 44, 800, 600)
GUICtrlSetResizing(-1, $GUI_DOCKALL)
GUICtrlSetStyle($oRDP_Ctrl , $WS_VISIBLE)
$oRDP.DesktopWidth = 800
$oRDP.DesktopHeight = 600
$oRDP.Fullscreen = False
$oRDP.ColorDepth = 16
$oRDP.AdvancedSettings3.SmartSizing = True
$oRDP.Server = $host
$oRDP.UserName = "" ; <--- Username
$oRDP.Domain = ""
$oRDP.AdvancedSettings2.ClearTextPassword = "" ; <--- Password
$oRDP.ConnectingText = "Connecting to " & $host
$oRDP.DisconnectedText = "Disconnected from " & $host
$oRDP.StartConnected = True
$oRDP.Connect()
$oShel = ObjCreate("shell.application")
$oShel_Ctrl = GUICtrlCreateObj($oShel, 64, 44, 800, 600)
GUICtrlSetStyle($oShel_Ctrl , $WS_VISIBLE)
GUISetState(@SW_SHOW, $hGUI)
Send ("#r") !!!!
While 1
$nMsg = GUIGetMsg()
Switch $nMsg
Case $GUI_EVENT_CLOSE
$oRDP.Disconnect()
Exit
EndSwitch
A: Did u try to do it with ShellExecute instead of opening the window first?
//Edit I just saw tht u asked the question before and tht u want to run the command at the other computer
| |
doc_23526937
|
library(shiny)
ui <- fluidPage(
tabPanel(title = "Hello world", value = "HB",
tabsetPanel(id="subtabs", type="pills",
tabPanel(title = "TAB 1", value = "ILPF",
br(),
h4("I like Pink floyd, my favourite album is 'The dark side of the moon'", style = "color:grey", align = "center"),
br()
),
tabPanel(title = "TAB 2", value = "FS",
br(),
h4("But my favourite song is 'Shine on you crazy diamond'", style = "color:grey", align = "center"),
br()
)
)
)
)
server <- function(input, output, session) {}
shinyApp(ui = ui, server = server)
The pills should be in the middle of the page
A: You can do so by adding some CSS to your app. tags$style('ul.nav-pills{display: flex !important;justify-content: center !important;}') does the trick.
library(shiny)
ui <- fluidPage(
tags$head(
tags$style('
ul.nav-pills{
display: flex !important;
justify-content: center !important;
}')
),
tabPanel(title = "Hello world", value = "HB",
tabsetPanel(id="subtabs", type="pills",
tabPanel(title = "TAB 1", value = "ILPF",
br(),
h4("I like Pink floyd, my favourite album is 'The dark side of the moon'", style = "color:grey", align = "center"),
br()
),
tabPanel(title = "TAB 2", value = "FS",
br(),
h4("But my favourite song is 'Shine on you crazy diamond'", style = "color:grey", align = "center"),
br()
)
)
)
)
server <- function(input, output, session) {}
shinyApp(ui = ui, server = server)
| |
doc_23526938
|
After the move, other is guaranteed to be empty(). 1
For move assignment, the oft-quoted:
other is in a valid but unspecified state afterwards. 2
Why is the state of other different in these two cases?
A: There are 2 popular ways to implement move in containers like vector that internally hold a pointer to the data:
*
*you can empty this, then copy the pointer (and size and capacity) from other to this and then set other members to nullptr/zero
*you can swap the data members (the pointers, size and capacity).
The standard wants to leave leeway to implementations to do either. These guarantees are the strongest guarantees it can make while allowing either methods of implementation:
*
*move constructor:
*
*1st method: leaves other in empty state
*2st method (swap): leaves other in empty state
*move assignment:
*
*1st method: leaves other in empty state
*2st method (swap): leaves other as a copy of initial this
| |
doc_23526939
|
static ConcurrentDictionary<string, string[]> data = new ConcurrentDictionary<string, string[]>();
public static async Task<string[]> GetStuffAsync(string key)
{
return data.GetOrAdd(key, async (x) => {
return await LoadAsync(x);
});
}
static async Task<string[]> LoadAsync(string key) {....}
but this gives me the error:
Cannot convert async lambda expression to delegate type 'System.Func'.
An async lambda expression may return void, Task or Task, none of which are convertible to 'System.Func'.
As I understand this is because GetOrAdd() is not asynchronous. How can I fix the issue?
Update:
LazyAsync suggested in the comments will work in my trivial example. Or, workaround like this (can definitely live with some overhead it introduces):
public static async Task<string[]> GetStuffAsync(string key)
{
string[] d = null;
if (!data.ContainsKey(key))
d = await LoadAsync(key);
return data.GetOrAdd(key, d);
}
The question then becomes did Microsoft just have no time to update all interfaces to support async or I'm trying to do something deeply wrong (and ConcurrentDictionary shouldn't have GetOrAddAsync()) ?
A: Async methods (or lambda) can only return void or Task or Task<T> but your lambda returns string[] and thus compiler prevents you.
await keyword is optimized to continue synchronously when the Task is already completed. So, one option is to store the Task itself in dictionary and don't worry about awaiting the completed Task again and again.
private static ConcurrentDictionary<string, Task<string[]>> data =
new ConcurrentDictionary<string, Task<string[]>>();
public static Task<string[]> GetStuffAsync(string key)
{
return data.GetOrAdd(key, LoadAsync);
}
And when you do
var item = await GetStuffAsync(...);
first time it will (a)wait till the cached Task finishes --There after it will continue synchronously.
You'll have to think about what should happen when LoadAsync fails. Because we're caching the Task returned by LoadAsync; if that fails we'll foolishly cache the failed Task. You may need to handle this.
| |
doc_23526940
|
class Foo
{
void assingTask()
{
pthread_t myThread;
int i;
pthread_create(myThread, NULL, task, (void*) i)
}
void * task(void *val)
{
//DO Stuff
}
};
I keep on getting the error that 'task' isn't a static function. Everything I have seen online mentions that there is a find this. The solutions to the problems are way beyond my skill level. Thank you for the help.
A: The problem is that pthread_create is a C function, not a C++ one, so using it from C++ can be tricky. The third argument needs to be a function pointer, but you're trying to call it with a method pointer which is not the same thing.
C++ does allow implicitly converting a static method pointer into a function pointer, so you can do what you want with that (that's why you get an error saying 'task' isn't static -- because if it was, it could be converted to a function pointer and used). Usually you then use the 4th argument to hold "this" so you can then call a non-static method from the static method
class Foo
{
void assingTask()
{
pthread_t myThread;
int i;
pthread_create(&myThread, NULL, start_task, this)
}
static void *start_task(void *this_) {
return static_cast<Foo *>(this_)->task();
}
void * task()
{
//DO Stuff
}
};
The above code has the problem that you "lose" the pthread_t handle (don't store it anywhere accessable), so you can't join or detach from the thread, but that could be fixed many ways.
A: Sure it is possible. Put your data in a structure and wrap it in a trampoline function to jump to your class function:
#include <pthread.h>
#include <stdint.h>
class Foo;
// the context passed to trapoline function
struct FooTaskTrampolineCtx {
Foo *obj;
void *val;
};
extern "C" void *FooTaskTrampoline(void *ptr);
struct Foo {
void assingTask() {
pthread_t myThread;
int i;
// note - memory allocated dynamically
struct FooTaskTrampolineCtx *c = new FooTaskTrampolineCtx;
c->obj = this;
c->val = (void*)(uintptr_t)i;
pthread_create(&myThread, NULL, FooTaskTrampoline, c);
}
void * task(void *val) {
//DO Stuff
}
};
extern "C" void FooTaskTrampolineCleanup(void *ptr) {
struct FooTaskTrampolineCtx *c = (struct FooTaskTrampolineCtx *)ptr;
delete c;
}
// trampolines to task method
extern "C" void *FooTaskTrampoline(void *ptr) {
struct FooTaskTrampolineCtx *c = (struct FooTaskTrampolineCtx *)ptr;
void *ret = NULL;
// remember to pick out the trash the PThread(TM) way
pthread_cleanup_push(FooTaskTrampolineCleanup, ptr);
ret = c->obj->task(c->val);
pthread_cleanup_pop(1);
return ret;
}
| |
doc_23526941
|
A: If the web service is a WSDL, you can test it using WcfTestClient utility that comes with .NET Framework. Go to .NET Command Prompt and type wcftestclient.. Here you can "Add Service" and type the full URL of the web service. You can even invoke the methods from here..
For consuming the web service, you can add web reference in your C# project which will create the proxy for you. In your program you will instantiate the proxy and call the method you need.
| |
doc_23526942
|
2013-06-06 08:57:08.716 KFBNewsroom[26898:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] loaded the "KFBMasterViewController" nib but didn't get a UITableView.'
The code for the split view is the same as it was in my test project so I can't figure out why it won't work here. Any ideas?
Here is the code from my didFinishLaunchingWithOptions method where I say what to load on different devices.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
self.viewController = [[KFBViewController alloc] initWithNibName:@"KFBViewController" bundle:nil];
self.window.rootViewController = self.tabBarController;
}
else
{
masterViewController.detailViewController = detailViewController;
self.splitViewController = [[UISplitViewController alloc] init];
self.splitViewController.delegate = detailViewController;
self.splitViewController.viewControllers = @[masterNavigationController, detailNavigationController];
self.window.rootViewController = self.splitViewController;
}
MasterViewController.h:
#import <UIKit/UIKit.h>
@class KFBDetailViewController;
@interface KFBMasterViewController : UITableViewController
@property (strong, nonatomic) KFBDetailViewController *detailViewController;
@end
MasterViewController.m:
#import "KFBMasterViewController.h"
#import "KFBDetailViewController.h"
#import "DetailViewManager.h"
@interface KFBMasterViewController () {
NSMutableArray *_objects;
NSMutableArray *menu;
}
@end
@implementation KFBMasterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Master", @"Master");
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// self.navigationItem.leftBarButtonItem = self.editButtonItem;
// UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];
// self.navigationItem.rightBarButtonItem = addButton;
menu = [NSMutableArray arrayWithObjects:@"Home", @"Public Affairs", @"Action Alerts", @"Market Updates", @"Ag Stories", @"KFB News", @"Member Benefits", @"Monthly Video", @"Photos", @"Social Media", @"About Us", @"Contact Us", @"KYFB.com", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return menu.count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UIImageView *image = [[UIImageView alloc]init];
image.image = [UIImage imageNamed:@"CellImage.png"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// NSDate *object = _objects[indexPath.row];
// cell.textLabel.text = [object description];
cell.textLabel.text = [menu objectAtIndex:indexPath.row];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.highlightedTextColor = [UIColor darkGrayColor];
cell.textLabel.font = [UIFont fontWithName:@"FranklinGothicStd-ExtraCond" size:20.0];
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundView = image;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
@end
A: You probably have to change the super-class of your rootViewController from UITableViewController to UIViewController.
| |
doc_23526943
|
Iam thinking of altering the column names after getting the column names from the user.
Is it possible.
which may be the efficient way to approach this problem.
For clarity...the problem is
I have 3 columns ( in my MYSQL table total of 6 )say COL1, COL2, COL3.
When i ask for input its is like this:
COL1: ___________________
COL2: ___________________
COL3: ___________________
Do you want more fields : y/N
If YES, then i want to add COL4, COL5,COL6 for them with a max of 3. ( i added a 6 columns in the table with the 3 columns with NULL values for the extra usage )
ALSO, i have to allow user to decide the COLUMN Name. In more clear way, if "y" is selected, then a popup with two fields - one for the Column name and its respective data
_________________ : ________________
. After that the column name should be able to show directly and ask just for the data.
COL1: ___________________
COL2: ___________________
COL3: ___________________
theCOLUMNNAME : ___________________
Do you want more fields : y/N
EDIT
I have used jQuery to add the field entries dynamically like this:
$(document).on('click', '.add_button', function(){
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/> <input type="text" name="field_name[]" value=""/><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="images/remove-icon.png"/></a></div>'; //New input field html
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
A: If you want to set a new name or id for the input you must to use
prompt
var newid = prompt("Set the new ID");
that allows you to enter a value and assign the value in a var and then set in the input.
Ok, let's do this!
First: replace the id:
var id = "input" + $(this).attr("id").replace("field","");
Second: ask the new ID, name or value
id = prompt("Set the new ID");
Third: assign the id and value for label
var label = $("<label for=\"" + id + "\">" + id + "</label>");
Fourth: assign the id, name or value to the input
input = $("<input type=\"text\" id=\"" + id + "\" name=\"" + id + "\"+ value=\"" + id + "\" />");
Here the code. I used this example: https://jsfiddle.net/qBURS/2/ and I modified the JS
HTML
<html>
<head></head>
<body>
<fieldset id="buildyourform">
<legend>Build your own form!</legend>
</fieldset>
<input type="button" value="Preview form" class="add" id="preview" />
<input type="button" value="Add a field" class="add" id="add" />
</body>
</html>
JS
<script>
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var fName = $("<input type=\"text\" class=\"fieldname\" />");
var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Paragraph</option></select>");
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(fType);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
$("#preview").click(function() {
$("#yourform").remove();
var fieldSet = $("<fieldset id=\"yourform\"><legend>Your Form</legend></fieldset>");
$("#buildyourform div").each(function() {
var id = "input" + $(this).attr("id").replace("field","");
id = prompt("Set the new ID");
var label = $("<label for=\"" + id + "\">" + id + "</label>");
var input;
switch ($(this).find("select.fieldtype").first().val()) {
case "checkbox":
input = $("<input type=\"checkbox\" id=\"" + id + "\" name=\"" + id + "\" />");
break;
case "textbox":
input = $("<input type=\"text\" id=\"" + id + "\" name=\"" + id + "\"+ value=\"" + id + "\" />");
break;
case "textarea":
input = $("<textarea id=\"" + id + "\" name=\"" + id + "\" ></textarea>");
break;
}
fieldSet.append(label);
fieldSet.append(input);
});
$("body").append(fieldSet);
});
});
</script>
| |
doc_23526944
|
Is there a cross-platform way of opening files with Xamarin.forms?
A: You will need to create custom platform code to enable a Share functionality.
I have a sample for this on GitHub here https://github.com/Depechie/XamarinFormsOffice but in essence you need to have following platform code in your project.
Here is one for Android
public class ShareService : IShare
{
public void Share(string filePath)
{
Java.IO.File file = new Java.IO.File(filePath);
Intent intent = new Intent(Intent.ActionView);
string mimeType = string.Empty;
if (Path.GetExtension(filePath).ToLower() == ".pdf")
mimeType = "application/pdf";
else if (Path.GetExtension(filePath).ToLower() == ".doc")
mimeType = "application/msword";
else if (Path.GetExtension(filePath).ToLower() == ".docx")
mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
else if (Path.GetExtension(filePath).ToLower() == ".xls")
mimeType = "application/vnd.ms-excel";
else if (Path.GetExtension(filePath).ToLower() == ".xlsx")
mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
else if (Path.GetExtension(filePath).ToLower() == ".ppt")
mimeType = "application/vnd.ms-powerpoint";
else if (Path.GetExtension(filePath).ToLower() == ".jpg")
mimeType = "image/jpeg";
var t = Uri.FromFile(file);
intent.SetDataAndType(t, mimeType);
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
this.StartActivity(intent);
}
}
public static class ObjectExtensions
{
public static void StartActivity(this object o, Intent intent)
{
var context = o as Context;
if (context != null)
context.StartActivity(intent);
else
{
intent.SetFlags(ActivityFlags.NewTask);
Application.Context.StartActivity(intent);
}
}
}
And this is one for iOS
public class ShareService : IShare
{
private UIDocumentInteractionController _controller;
public void Share(string filePath)
{
UIApplication.SharedApplication.InvokeOnMainThread(() =>
{
_controller = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(filePath));
_controller.Name = Path.GetFileName(filePath);
var window = UIApplication.SharedApplication.KeyWindow;
var subviews = window.Subviews;
var view = subviews.Last();
var frame = view.Frame;
frame = new CGRect((float)Math.Min(10, frame.Width), (float)frame.Bottom, 0, 0);
_controller.PresentOptionsMenu(frame, view, true);
});
}
}
| |
doc_23526945
|
I'm currently looping over all of the Customers like this:
<% @customers.where(:private => false).each do |single_customer| %>
My question is how can I accomplish when one of the 3 users is signed in that :private => false gets changed to @customers.each do |single_customer| because then I don't want to filter the private attribute anymore.
A: you need to change the build up of the loop. This snippet is a bit of meta programming, but you can do it like this:
# in the controller for example.
@customers = Customer.where(private: false)
@customers = Customer.all if current_user.is_my_special_user?
In the view you then simply do this: <% @customers.find_each do |customer| %>
*
*use find_each for better performance if your collection is huge.
*by default you use the private: false
*if you detect your user is logged in, you overwrite the @customers
| |
doc_23526946
|
from openpyxl import load_workbook
wb = load_workbook("convert_file.xlsx",data_only=True)
ws = wb.active
sheetname_row_list:list =[]
for row in ws.iter_rows(min_row=2, max_row=7, min_col=1, max_col=6):
row = [cell.value for cell in row]
sheetname_row_list.append(row)
from yattag import Doc, indent
doc, tag, text = Doc().tagtext()
for row in sheetname_row_list:
with tag("column0"):
text(row[0])
with tag("column1"):
text(row[1])
with tag("column2"):
text(row[2])
with tag("column3"):
text(row[3])
with tag("column4"):
text(row[4])
with tag("column5"):
text(row[5])
result = indent(
doc.getvalue(),
indentation = ' ',
indent_text = False
)
with open("result_file.xml","w") as f:
f.write(result)
How can I now create several XML files from several XLSX files with all the same structure?
I have "convert_file.xlsx" / "convert_file_2.xlsx" / "convert_file_3.xlsx"... and want to get "result_file.xml" / "result_file_2.xml" / "result_file_3.xml"...
A: I suggest using pathlib and something like:
from pathlib import Path
source_directory = Path('.') # Pointing to the XLSX files
for filename in source_directory.glob('*.xlsx'):
# Call to your conversion code
...
resultname = f'{filename.stem.replace("convert", "result")}.xml'
# Save to file using resultname
...
Happy coding.
Edit: Included a way of changing the file extension from .xlsx to .xml
| |
doc_23526947
|
<div STYLE="display:inline-block;-webkit-column-count:2;-moz-column-count:2;column-count:2;-webkit-column-gap:0;-moz-column-gap:0;column-gap:0;height:100;width:100%;background-color:red;">
<div STYLE="padding:10px;-webkit-column-count: 2 ; -moz-column-count: 2;column-count: 2;overflow:auto;display:inline-block;position:relative;height:auto;width:100%;background-color:#FFFFFF;border: 1px solid #000000;">
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
</div>
<div STYLE="padding:10px;-webkit-column-count: 2 ; -moz-column-count: 2;column-count: 2;overflow:auto;display:inline-block;position:relative;height:auto;width:100%;background-color:#FFFFFF;border: 1px solid #000000;">
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
</div>
<div STYLE="padding:10px;-webkit-column-count: 2 ; -moz-column-count: 2;column-count: 2;overflow:auto;display:inline-block;position:relative;height:100px;width:100%;background-color:#FFFFFF;border: 1px solid #000000;">
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
</div>
<div STYLE="padding:10px;-webkit-column-count: 2 ; -moz-column-count: 2;column-count: 2;overflow:auto;display:inline-block;position:relative;height:auto;width:100%;background-color:#FFFFFF;border: 1px solid #000000;">
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
<BR>TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT-TEXT
</div>
A: The overflow attribute, coupled with nested column layouts, appears to be to blame.
First, let's setup a simpler, cleaner version of the problem.
Run the snippet and note that while the borders of the elements are visible, the contents of the second column are not visible (testing in Chrome 62.0.3202.89).
.outer-split {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
-webkit-column-gap: 0;
-moz-column-gap: 0;
column-gap: 0;
}
.inner-split {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
border: 1px solid #ddd;
overflow: auto;
}
<div class="outer-split">
<div class="inner-split">
column 1
<br> column 1
</div>
<div class="inner-split">
column 2
<br> column 2
</div>
<div class="inner-split">
column 3
<br> column 3
</div>
<div class="inner-split">
column 4
<br> column 4
</div>
</div>
Take away the overflow attribute, and the content is visible.
.outer-split {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
-webkit-column-gap: 0;
-moz-column-gap: 0;
column-gap: 0;
}
.inner-split {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
border: 1px solid #ddd;
}
<div class="outer-split">
<div class="inner-split">
column 1
<br> column 1
</div>
<div class="inner-split">
column 2
<br> column 2
</div>
<div class="inner-split">
column 3
<br> column 3
</div>
<div class="inner-split">
column 4
<br> column 4
</div>
</div>
My guess is that the due to the nested column layout, the browser is calculating that all of the content is "overflow" and therefore hides it. Setting overflow:visible causes the hidden content to display.
I hesitate to say that this is a bug; it appears that the browser is allocating the space for the content but still clipping it. I tried giving the contents explicit height/width (see Advanced Example), but the text is still hidden.
| |
doc_23526948
|
@Query(value="UPDATE tableExample "
+ "SET tableExample.DTFINE = sysdate "
+ "WHERE tableExample.prv = :idPrv AND tableExample.DTFINE IS NULL", nativeQuery=true)
public void updateDtFine( Long idPrv);
But for some reason, I'm getting this error:
ORA-01002: cursore non valido
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:494)
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:446)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1054)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:623)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:226)
at oracle.jdbc.driver.T4CPreparedStatement.fetch(T4CPreparedStatement.java:1023)
at oracle.jdbc.driver.OracleStatement.fetchMoreRows(OracleStatement.java:3353)
at oracle.jdbc.driver.InsensitiveScrollableResultSet.fetchMoreRows(InsensitiveScrollableResultSet.java:736)
at oracle.jdbc.driver.InsensitiveScrollableResultSet.absoluteInternal(InsensitiveScrollableResultSet.java:692)
at oracle.jdbc.driver.InsensitiveScrollableResultSet.next(InsensitiveScrollableResultSet.java:406)
at weblogic.jdbc.wrapper.ResultSet_oracle_jdbc_driver_ForwardOnlyResultSet.next(Unknown Source)
at org.hibernate.loader.Loader.processResultSet(Loader.java:1004)
at org.hibernate.loader.Loader.doQuery(Loader.java:964)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2815)
... 88 more
Caused by: Error : 1002, Position : 0, Sql = UPDATE tableExample SET
tableExample.DTFINE = sysdate WHERE tableExample.prv = :1 AND tableExample.DTFINE
IS NULL, OriginalSql = UPDATE tableExample SET tableExample.DTFINE = sysdate WHERE
tableExample.prv = ? AND tableExample.DTFINE IS NULL, Error Msg = ORA-01002:
cursore non valido
I really don't understand why it's not working. I even tried the same update query directly on oracle sql developer
UPDATE tableExample SET tableExample.DTFINE = sysdate WHERE tableExample.prv = 18
AND tableExample.DTFINE IS NULL
and it works with no errors.
Is there something i'm missing? And what exactly means "not valid cursor"?
| |
doc_23526949
|
html
<ul class='tabs'>
<li><a href='#tab1'>Tab 1</a></li>
<li><a href='#tab2'>Tab 2</a></li>
<li><a href='#tab3'>Tab 3</a></li>
</ul>
<div id='tab1'>
<ul class= "set2">
<li> test 1<asp:TextBox runat="server" ID="test1" /></li>
<li> test 2<asp:TextBox runat="server" ID="test2" /></li>
</ul>
</div>
<div id='tab3'>
<ul class= "set2">
<li> test 3<asp:TextBox runat="server" ID="test3" /></li>
<li> test 4<asp:TextBox runat="server" ID="test4" /></li>
</ul>
</div>
<div id='tab3'>
<ul class= "set">
<li> test 5<asp:TextBox runat="server" ID="test5" /></li>
<li> test 6<asp:TextBox runat="server" ID="test6" /></li>
</ul>
</div>
this is jquery
// Wait until the DOM has loaded before querying the document
$(document).ready(function(){
$('ul.tabs').each(function(){
// For each set of tabs, we want to keep track of
// which tab is active and it's associated content
var $active, $content, $links = $(this).find('a');
// If the location.hash matches one of the links, use that as the active tab.
// If no match is found, use the first link as the initial active tab.
$active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
$active.addClass('active');
$content = $($active.attr('href'));
// Hide the remaining content
$links.not($active).each(function () {
$($(this).attr('href')).hide();
});
// Bind the click event handler
$(this).on('click', 'a', function(e){
// Make the old tab inactive.
$active.removeClass('active');
$content.hide();
// Update the variables with the new link and content
$active = $(this);
$content = $($(this).attr('href'));
// Make the tab active.
$active.addClass('active');
$content.show();
// Prevent the anchor's default click action
e.preventDefault();
});
});
});
</script>
and this css
* {padding:0; margin:0;}
html {
background:url(/img/tiles/wood.png) 0 0 repeat;
padding:15px 15px 0;
font-family:sans-serif;
font-size:14px;
}
p, h3 {
margin-bottom:15px;
}
div {
padding:10px;
width:600px;
background:#fff;
}
.tabs li {
list-style:none;
display:inline;
}
.tabs a {
padding:5px 10px;
display:inline-block;
background:#666;
color:#fff;
text-decoration:none;
}
.tabs a.active {
background:#fff;
color:#000;
}
A: Use this javascript:
Demonstration.
// Wait until the DOM has loaded before querying the document
$(document).ready(function () {
$('ul.tabs').each(function () {
// For each set of tabs, we want to keep track of
// which tab is active and it's associated content
var $active, $content, $links = $(this).find('a');
// If the location.hash matches one of the links, use that as the active tab.
// If no match is found, use the first link as the initial active tab.
$active = $($links.filter('[href="' + location.hash + '"]')[0] || $links[0]);
$active.addClass('active');
$content = $($active.attr('href'));
// Hide the remaining content
$links.not($active).each(function () {
$($(this).attr('href')).hide();
});
// Bind the click event handler
$(this).on('focus', 'a', function (e) { //from click handler to focus handler
// Make the old tab inactive.
$active.removeClass('active');
$content.hide();
// Update the variables with the new link and content
$active = $(this);
$content = $($(this).attr('href'));
// Make the tab active.
$active.addClass('active');
$content.show();
// Prevent the anchor's default click action
e.preventDefault();
});
});
});
And this HTML:
<ul class='tabs'>
<li><a href='#tab1' tabindex="1">Tab 1</a> <!--tabindex added so that it could be accessed by pressing tab key-->
</li>
<li><a href='#tab2' tabindex="2">Tab 2</a> <!--tabindex added so that it could be accessed by pressing tab key-->
</li>
<li><a href='#tab3' tabindex="3">Tab 3</a> <!--tabindex added so that it could be accessed by pressing tab key-->
</li>
</ul>
<div id='tab1'>
<ul class="set2">
<li>test 1
<asp:TextBox runat="server" ID="test1" />
</li>
<li>test 2
<asp:TextBox runat="server" ID="test2" />
</li>
</ul>
</div>
<div id='tab3'>
<ul class="set2">
<li>test 3
<asp:TextBox runat="server" ID="test3" />
</li>
<li>test 4
<asp:TextBox runat="server" ID="test4" />
</li>
</ul>
</div>
<div id='tab3'>
<ul class="set">
<li>test 5
<asp:TextBox runat="server" ID="test5" />
</li>
<li>test 6
<asp:TextBox runat="server" ID="test6" />
</li>
</ul>
Code Explanation
Explanation of JS:
I have changed the event handler from click to focus so that when the div would be focused the script could run rather then on clicking it.
Explanation of HTML:
I have added tabindex to the tabs so that they could be accessed by using the tab key.
| |
doc_23526950
|
ACTUAL CODE:
df -PH | grep -vE '^Filesystem|tmpfs|cdrom|loop' | awk '{ print $5 " " $1 " " $6}' | while read output;
do
proc=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
partition=$(echo $output | awk '{ print $2 }' )
mountp=$(echo $output | awk '{ print $3 }' )
ohostn=$(checkOtherHostname)
if [ $proc -ge $THRESHOLD_HD ]; then
printf "%20s [%6s] [%20s] %4s%% \"%s\"\n" "$(hostname)" "$ohostn" "$mountp" "$proc" "$partition"
sudo du -sh $mountp/*
fi
done
Result is in the OUTPUT below.
Then I tried differently by putting in a second if statement underneath the first if statement and moved the sudo command in it and the output was still the same!
df -PH | grep -vE '^Filesystem|tmpfs|cdrom|loop' | awk '{ print $5 " " $1 " " $6}' | while read output;
do
proc=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
partition=$(echo $output | awk '{ print $2 }' )
mountp=$(echo $output | awk '{ print $3 }' )
ohostn=$(checkOtherHostname)
if [ $proc -ge $THRESHOLD_HD ]; then
printf "%20s [%6s] [%20s] %4s%% \"%s\"\n" "$(hostname)" "$ohostn" "$mountp" "$proc" "$partition"
fi
if [ $proc -ge $THRESHOLD_HD ]; then
sudo du -sh $mountp/*
fi
done
OUTPUT:
1.1T /data/svn_repo_01/repos
16K /data/svn_repo_01/lost+found
2.7G /data/svn_repo_01/csvn
4.0K /data/svn_repo_01/migration
4.0K /data/svn_repo_01/tmp
vmappp21 [svntoy] [ /data/svn_repo_01] 70% "/dev/sde1"
A: Short answer: It shouldn't happen.
I couldn't reproduce your issue on my environment, but you didn't give us some relevant information:
*
*bash --version. E.g. GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
*What checkOtherHostname does?
*If the current stdout is being redirected in a higher level (e.g. through pipes or using exec >)
About performance
Nothing to do with your question, but I noticed you used the folowing commands:
*
*df, grep (one execution)
*awk (4 times: 3 executions for each df row)
*cut, echo, hostname and checkOtherHostname (one execution for each df row)
*printf, sudo, du (when proc >= THRESHOLD_HD)
As it's a small script without special performance needs, that shouldn't be a problem, but if you intend to use the same approach in bigger scripts or processing many records. It can be an issue.
So I made this reduced version of your script, using only the minimal quantity of commands:
*
*df, hostname and checkOtherHostname (one time)
*printf, sudo, du (when proc >= THRESHOLD_HD)
hostname="$(hostname)"
ohostn="$(checkOtherHostname)"
df -PH | while read partition size used avail proc mountp; do
if ! [[ "$partition$mountp" =~ "Filesystem|tmpfs|cdrom|loop" ]] && [ ${proc%%%} -ge $THRESHOLD_HD ]; then
printf "%20s [%6s] [%20s] %4s \"%s\"\n" "$hostname" "$ohostn" "$mountp" "$proc" "$partition"
sudo du -sh $mountp/*
fi
done
| |
doc_23526951
|
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddhhmmss"];
NSString *keyDate = [dateFormatter stringFromDate:[NSDate date]];
and have been getting the result: 20140926125522.
But after the update I am now getting: 2014092612:55:22.
I am then unable to convert the keydate to a NSNumber as it now contains :.
Is anyone else getting this?
** EDIT **
After reading the comments i decided to go into the device settings and in the time and settings section turned the Set Automatically to off and the issue went away. I then turned it back on and the issue did not reappear.
Thanks for all the help.
A: An immediate fix could be the following:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddhhmmss"];
NSString *keyDate = [dateFormatter stringFromDate:[NSDate date]];
keyDate = [keyDate stringByReplacingOccurrencesOfString:@":" withString:@""];
This is not a solution however and should be fixed by apple in upcoming release
EDIT
I just checked in iPhone 4s with 8.0.2 (12A405) and can't reproduce the problem , using XCode 6.1 beta 2. it produces desired output
Printing description of keyDate:
20140926061051
EDIT 2
Checked in two other devices , same result, so i can say it is not an apple bug
| |
doc_23526952
|
TelephonyManager tm=(TelephonyManager) getSystemService(Context.TELECOM_SERVICE);
String deviceId=tm.getDeviceId();
to get device IMEI.
But is shows warning
field requires API level 21 (current min is 14):
android.content.Context#TELECOM_SERVICE
What does it mean? And how to solve this?
I am using
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="22" />
And also this is not working:
Toast.makeText(getApplicationContext(), deviceId, Toast.LENGTH_LONG).show();
A: Use TELEPHONY_SERVICE instead of TELECOM_SERVICE like below:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// get IMEI
String imei = tm.getDeviceId();
| |
doc_23526953
|
Ive incorporated sqlite to fill the tableview, but currently the search is using substrings with .contains.
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredFood = food.filter { candy in
return candy.name.lowercaseString.containsString(searchText.lowercaseString)
}
tableView.reloadData()
}
Ive looked up a few different ways, NSPredicates and Regex, but Im not quite sure how to incorporate them correctly, or if thats what I even need to do.
Ex.Cell is "Stackoverflow is so amazing!"
If i search for Stackoverflow, the search is fine, but if I search "so is" I get no results.
A: You are looking for a more customized search method, which you would have to develop yourself.
For the example you provided, this code searches for each individual word to match:
let searchTerms = searchText.componentsSeparatedByString(" ").filter { $0 != "" }
filteredFood = food.filter { candy in
for term in searchTerms{
if !candy.name.lowercaseString.containsString(term.lowercaseString){
return false
}
}
return true
}
A: You can use regex for this using NSRegularExpression. For a regex to do a keyword search, I think the best way to do it is to do it in the following way: (str1|str2|str3).
So, in swift you can create replace the spaces with '|' and then use regular expressions:
let rtext = searchText.stringByReplacingOccurrencesOfString(" ", withString: "|");
let regex = NSRegularExpression(pattern: "(\(rtext))", .CaseInsensitive);
filteredFood = food.filter { candy in
return regex.numberOfMatchesInString(candy.name, options: 0, range: NSRange(0, candy.name.characters.count) > 0;
}
(Note haven't tested the code)
A: You can search in more than one label for example you have a class that contains state and city. So if the city does not exist it shows the rest of the cities in the state.
Here is what I am taking about:
// Set up the search text
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// Create and divid the string into substring such as "You are" to "You" and "are"
let searchTerm = searchText.components(separatedBy: " ").filter{ $0 != "" }
// Whatever is being filtered is assigned to rilteredArrayPropertys
filteredArrayPropertys = arrayPropertys.filter({ (state) -> Bool in
// Search each term or substring
for term in searchTerm{
// Check which substring is equal state.propertyState, and if it statsifies it will return and assign to state.propertyState.
// .range(of: ): is what is being typed into search bar. state.propertyState is what has been setted.
if (state.propertyState.lowercased().range(of: term.lowercased()) != nil) || (state.propertyCity.lowercased().range(of: term.lowercased()) != nil) {
return true
}
}
return false
})
if searchText != "" {
shouldShowSearchResults = true
self.tableView.reloadData()
}
else {
shouldShowSearchResults = false
self.tableView.reloadData()
}
}
| |
doc_23526954
|
As a note I was using a JLayeredPane, however I need the TabbedPane to fill the parent component, and it didn't seem like it would work without some finagling.
Anyway it seems that when you leave the alignments alone the behavior works as expected (the button floats over the background). However when using any sort of alignment (it's my understanding that this is how you set position with this layout manager), it will shrink the background to the edge of where the button should be.
Here's some sample code.
import java.awt.Color;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
Container c = frame.getContentPane();
c.setLayout(new OverlayLayout(c));
JButton button = new JButton("Test");
JPanel background = new JPanel();
background.setBackground(Color.BLUE);
background.setSize(500, 500);
// toggle the following between 0 and 100 to see the described behavior
background.setAlignmentX(100);
frame.add(background);
frame.add(button);
frame.pack();
frame.setSize(800, 800);
frame.setVisible(true);
}
}
Any suggestions would be appreciated.
A: You can use the method setGlassPane for put a pane over other in a frame. Check in http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html
A: *
*mistake is using setBound() where is useless and contraproductive for this LayoutManager
*use implemented methods in the API about setMaximumSize()
*then there no issue
if you want to really to create JComponents that overlay another you have look at
*
*JLayeredPane --> outdated and you can use only up to 6.th LayeredPanes
*JXLayer for Java6 or direct implementations as JLayer in Java7
*for simple overlay you can use GlassPane too,
| |
doc_23526955
|
In touchesBegan, I set the backgroundColor from white to green by using self.backgroundColor = [UIColor greenColor] ... in the touchesEnd I reset the color to white.
It works but very slowly. By tapping the view, it takes 0.5 - 1.0 sec until I see the green color.
Selecting a cell in a UITableView it's much faster.
A: Try this:
self.view.userInteractionEnabled = YES;
UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(doCallMethod:)];
recognizer.delegate = self;
recognizer.minimumPressDuration = 0.0;
[self.view addGestureRecognizer:recognizer];
- (void)doCallMethod:(UILongPressGestureRecognizer*)sender {
if(sender.state == UIGestureRecognizerStateBegan){
NSLog(@"Begin");
self.view.backgroundColor = [UIColor greenColor];
}else if (sender.state == UIGestureRecognizerStateEnded){
NSLog(@"End");
self.view.backgroundColor = [UIColor whiteColor];
}
}
Note:
It will work more faster.
A: You should use a gesture recognizer as TheBurgerShot suggested but I recommend you an UILongPressGestureRecognizer. Something like:
UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(changeColor:)];
gesture.minimumPressDuration = 0.f;
[self.yourView addGestureRecognizer:gesture];
in your viewDidLoad. And:
-(void) changeColor:(UIGestureRecognizer *)gestureRecognizer{
if (gestureRecognizer.state == UIGestureRecognizerStateBegan){
self.yourView.backgroundColor = [UIColor greenColor];
}
else if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
self.yourView.backgroundColor = [UIColor whiteColor];
}
}
| |
doc_23526956
|
Person:
ID Name Age
1 Jack 25
2 Jill 23
Tests:
ID PersonID TestID Result
1 1 1 125
2 1 2 120
3 1 3 75
4 2 1 90
5 2 2 95
6 2 3 7.2
Is there a way to retrieve that data with a single statement in a way that each record in the master table is presented in a single row? Something like this:
PersonID Name Age Test1 Test2 Test3
1 Jack 25 125 120 75
2 Jill 23 90 95 7.2
So far, the only way I have come up with has been to create a function which iterates through the detail records and fills a temporary table. Not very elegant.
Thanks in advance
A: In order to get this result, you will need to use the PIVOT function. This transforms the data from multiple rows into columns.
If you know the values ahead of time or you will have a limited number of TestId values, then you can hard-code the query making the query static.
SELECT Name,
Age,
[1] AS Test1,
[2] AS Test2,
[3] AS Test3
FROM
(
SELECT P.Name, P.Age, t.TestID, t.Result
FROM tests t
INNER JOIN person P
ON p.ID = t.PersonID
) T
PIVOT
(
sum(Result)
FOR TestID IN ([1], [2], [3])
) piv;
See SQL Fiddle with Demo.
But if you have an unknown number of TestId values, then you will want to use dynamic SQL to generate the list of columns at run-time. You Code will be:
DECLARE @cols AS NVARCHAR(MAX),
@colNames AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(testId)
from tests
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colNames = STUFF((SELECT distinct ',' + QUOTENAME(testId) +' as Test'+cast(testId as varchar(10))
from tests
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Name, age, ' + @colnames + ' from
(
select P.Name, P.Age, t.TestID, t.Result
from tests t
inner join person P
on p.ID = t.PersonID
) x
pivot
(
sum(Result)
for TestID in (' + @cols + ')
) p '
execute(@query)
See SQL Fiddle with Demo.
They both will generate the same result, difference being that the dynamic one will increase/decrease the columns if the number of test ids changes:
| NAME | AGE | TEST1 | TEST2 | TEST3 |
--------------------------------------
| Jack | 25 | 125 | 120 | 75 |
| Jill | 23 | 90 | 95 | 7.2 |
A: You can do a pivot on the TestID
Here you go... its kinda messy but you can improve on it :)
SELECT Name,Age,SUM([1]) AS Test1,SUM([2]) AS Test2,SUM([3]) AS Test3
FROM(
SELECT P.Name,P.Age,Te.ID, TestID,Result
FROM Test Te
INNER JOIN dbo.Person P ON P.ID=Te.PersonID) T
PIVOT(MAX(T.Result) FOR TestID IN([1],[2],[3])) AS pvt
GROUP BY Name,Age
heres some links
http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
http://www.codeproject.com/Questions/393632/How-to-use-Pivot-in-SQL
http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/
| |
doc_23526957
|
The application does, in development, register properly, linking a customer ID in our system to the token string from the phone.
However, this does not allow me to determine programatically from our server which push notification server to use.
A: I'm not sure if I have your question right, but as per Apple's doc Local and Push Notification Programming Guide: The Notification Payload
Providers can specify custom payload values outside the Apple-reserved
aps namespace.
So all you need to do is craft your custom payload to indicate which server the notification was pushed from, and read it when it gets to the App.
| |
doc_23526958
|
In the following code can anyone explain the pragmatic difference between FirstChild and SecondChild. It's clear from experiments that both "work" and arguably SecondChild is marginally more efficient. But is there something that I'm missing about the way these two behave? Are they different and how are they different?
import collections
class Parent:
def send_message(self, message: str):
pass
class FirstChild(Parent):
def __init__(self):
self.message_queue = collections.deque()
def send_message(self, message: str):
self.message_queue.append(message)
class SecondChild(Parent):
def __init__(self):
self.message_queue = collections.deque()
self.send_message = self.message_queue.append
A: FirstChild creates a descriptor in the class called send_message. When you do instance.send_message, the interpreter first searches the instance __dict__ for the name, then the class. When it's found in the class, the function is bound to the instance to create a method object that doesn't accept self. It happens every time you do the lookup, and it looks something like
method = type(instance).send_message.__get__(type(instance), instance)
SecondChild assigns a bound method as the attribute send_message in the instance. It cuts out the lookup in its own class object, as well as the lookup in the deque class object, and binding. That is probably why it appears marginally more efficient.
A major practical difference between these approaches is that send_message in SecondChild is not overridable. Since functions are non data descriptors (they have a __get__ method but not __set__ (and yes, functions have a class type and methods, like any other object)), the instance attribute send_message in SecondChild will always trump any class-level function. This means that a child of SecondChild that calls the parent __init__ method will hide any implementation of send_message it creates.
You will likely find the official descriptor guide to be quite informative: https://docs.python.org/3/howto/descriptor.html
| |
doc_23526959
|
Sub CopyPartOfFilteredRange()
Dim ws1 As Worksheet
Dim filterRange As range
Dim copyRange As range
Dim lastRow As Long
Set ws1 = ThisWorkbook.Sheets("Sheet 1")
ws1.AutoFilterMode = False
lastRow = ws1.range("A" & ws1.Rows.Count).End(xlUp).Row
Set filterRange = ws1.range("A1:N" & lastRow)
Set copyRange = ws1.range("A2:N" & lastRow)
filterRange.AutoFilter Field:=2, Criteria1:="313"
filterRange.AutoFilter Field:=3, Criteria1:="=1", _
Operator:=xlAnd, Criteria2:="=2"
lastRow = ws1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ws1.Cells(lastRow, 1).Select
ws1.Paste
ws1.AutoFilterMode = False
End Sub
A: I believe that because you are redefining the last row after a filter, using xlUp will miss the last row since it may be hidden in the filter. I would suggest using
lastRow = lastRow + 1
since you already have the last row of the range defined and you just want to past one row below that.
Your second filter, by the way, will filter on nothing because no cell will be both equal to 1 and equal to 2. Not sure what you want there. In any case, like I said in my comment, I don't believe you are copying anything, so you will need
filterRange.Copy
after the filter. I am not sure I would recommend copying and pasting like this, but I am going to try to just modify your code instead of rewriting it.
Also, I don't believe that
Set copyRange = ws1.range("A2:N" & lastRow)
is needed at all and can be deleted.
This is what I have in full
Sub CopyPartOfFilteredRange()
Dim ws1 As Worksheet
Dim filterRange As Range
Dim lastRow As Long
Set ws1 = Worksheets("Sheet1")
ws1.AutoFilterMode = False
lastRow = ws1.Range("A" & ws1.Rows.Count).End(xlUp).Row
Set filterRange = ws1.Range("A1:N" & lastRow)
filterRange.AutoFilter Field:=2, Criteria1:="313"
filterRange.Copy
lastRow = lastRow + 1
ws1.Cells(lastRow, 1).Select
ws1.Paste
ws1.AutoFilterMode = False
End Sub
A: you must:
*
*change xlAnd into xlOr
*increase lastRow of 1 to reference the cell to paste in
*use SpecialCells(xlCellTypeVisible) to select filtered cells (if any!)
try his
Option Explicit
Sub CopyPartOfFilteredRange()
Dim lastRow As Long
With ThisWorkbook.Sheets("Sheet 1")
.AutoFilterMode = False
lastRow = .Range("A" & .Rows.Count).End(xlUp).row
With .Range("A1:N" & lastRow)
.AutoFilter Field:=2, Criteria1:="313"
.AutoFilter Field:=3, Criteria1:="1", Operator:=xlOr, Criteria2:="2"
If Application.WorksheetFunction.Subtotal(103, .Cells.Resize(, 1)) > 1 Then 'count visible cells in column "A" other than the header
.Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Copy .Cells(lastRow + 1, 1)
End If
End With
.AutoFilterMode = False
End With
End Sub
| |
doc_23526960
|
I tried deleting cache, and deactivating all plugins to see whether that's causing the issue. But the issue still persists.
Can someone please help me out here?
This is the page I need help with - https://www.writtenlyhub.com/contact/
A:
window.onload = function() {
const $form = document.querySelector('form');
$form.addEventListener('submit', (event) => {
event.preventDefault();
console.log('prevented submit by code for demo');
});
};
Did you not payed your developer? That code looks intentionally put there.
| |
doc_23526961
|
import SwiftUI
class ModelObject : ObservableObject{
@Published var text = "Model Text"
}
struct MyTextView : UIViewRepresentable {
@ObservedObject var modelObject : ModelObject
func makeUIView(context: Context) -> UITextView {
let result = UITextView()
result.isEditable = true
return result
}
func updateUIView(_ view: UITextView, context: Context) {
view.text = modelObject.text
}
}
struct BugDemoView : View{
@ObservedObject var modelObject : ModelObject
var body : some View{
VStack{
MyTextView(modelObject: modelObject)
Button(action: {
self.modelObject.text = "ouch"
}){
Text("Button")
}
}
}
}
#if DEBUG
var mo = ModelObject()
struct BugDemoView_Preview: PreviewProvider {
static var previews: some View {
BugDemoView(modelObject: mo)
}
}
#endif
A: It looks like some kind of bug of SwiftUI, but there are two workarounds:
*
*Pass string as @Binding to MyTextView:
struct MyTextView : UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> UITextView {
let result = UITextView()
result.isEditable = true
return result
}
func updateUIView(_ view: UITextView, context: Context) {
view.text = text
}
}
struct BugDemoView : View{
@ObservedObject var modelObject = ModelObject()
var body : some View{
VStack{
MyTextView(text: $modelObject.text)
Button(action: {
self.modelObject.text = "ouch"
}){
Text("Button")
}
}
}
}
*Pass string to MyTextView:
struct MyTextView : UIViewRepresentable {
var text: String
func makeUIView(context: Context) -> UITextView {
let result = UITextView()
result.isEditable = true
return result
}
func updateUIView(_ view: UITextView, context: Context) {
view.text = text
}
}
struct BugDemoView: View{
@ObservedObject var modelObject = ModelObject()
var body: some View{
VStack{
MyTextView(text: modelObject.text)
Button(action: {
self.modelObject.text = "ouch"
}){
Text("Button")
}
}
}
}
A: I had mixed results using the following. I'm pretty sure there is some kind bug with UIViewRepresentable
It worked for someviews, but then I pushed the exact same view again and the view model wouldn't update. Very strange...
Hopefully they release a SwiftUI TextView soon.
struct TextView: UIViewRepresentable {
@Binding var text: String
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> UITextView {
let myTextView = UITextView()
myTextView.delegate = context.coordinator
myTextView.font = UIFont(name: "HelveticaNeue", size: 15)
myTextView.isScrollEnabled = true
myTextView.isEditable = true
myTextView.isUserInteractionEnabled = true
myTextView.backgroundColor = UIColor(white: 0.0, alpha: 0.05)
return myTextView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
}
class Coordinator: NSObject, UITextViewDelegate {
var parent: TextView
init(_ uiTextView: TextView) {
self.parent = uiTextView
}
func textViewDidChange(_ textView: UITextView) {
print("text now: \(String(describing: textView.text!))")
self.parent.text = textView.text
}
}
}
A: In my case I need to pass in an observable object into the uiViewRepresentable, so same case as mentioned by Rivera... When a @Published property of that observable object changes, updateUIView is called in the simulator but not on a real device... I'm using the latest Xcode 11.4 but admittedly on a device running iOS 13.3 (13.4.1 not installed yet, so I haven't checked if that bug has been eliminated or not). What solved my problem is the following: change the struct MyTextView into a final class (the final keyword is important), then add an initialiser. It is not even necessary to call .objectWillChange.send() on the observed object right before the change of the published var is triggered.
A: I noticed via print statements that makeUIView wasn't being called again after the first URL was successfully loaded. So upon the URL changing, my WebView was remaining on the first URL.
I modified my updateUIView method - which WAS being called when the URL was updated after the first successful load - to check if there was a difference between the active url and the new url. If there was a difference I updated the page with the correct url.
Here is my sample updateUIView method:
let request: URLRequest
func updateUIView(_ uiView: WKWebView, context: Context) {
if uiView.canGoBack, webViewStateModel.goBack {
uiView.goBack()
webViewStateModel.goBack = false
} else {
if(uiView.url?.absoluteString == request.url?.absoluteString){
print("The urls are equal")
} else {
print("The urls are NOT equal")
uiView.load(request)
}
}
}
| |
doc_23526962
|
The top image doesn't have hint/description, while the Android stock ones have.
| |
doc_23526963
|
A: Place your URL in place of IMAGE_URL then Glide will do rest of work
Glide.with(context)
.load(IMAGE_URL)
.into(imageView);
Dependency if it's missing in build.gradle
implementation 'com.github.bumptech.glide:glide:4.13.0'
A: For Kotlin use Coil
In your app level gradle file add following line.
implementation("io.coil-kt:coil:2.1.0")
Then to load an image
imageView.load("https://www.example.com/image.jpg")
| |
doc_23526964
|
I am paranoid to touch the script and mess it up.
A: You don't need JavaScript for this. It's just plain and simple CSS.
a {color: #333;}
a:hover {color: #f0f0f0;}
a:active {color: #ccc;}
A: Jezen have already answered you but it seems that you aren't sure what to do with the CSS.
Ok, let's do it step by step. Here's the selector the anchor that says "Click to Refresh"
.short_explanation a {color: #ccc;}
.short_explanation a:hover {color: #f0f0f0;}
.short_explanation a:active {color: #ccc;}
Now where to put this ? I guess there's a file named contact.css for that contact form, open that file to edit it and paste the CSS below or above the other CSS rules in the file.
| |
doc_23526965
|
What I want to do now is when the tableview shows up, it immediately scrolls down to the month of today. I have the following function for that.
-(void)scrollToPosition{
NSDate *now = [NSDate date];
NSString *strDate = [[NSString alloc] initWithFormat:@"%@",now];
NSArray *arr = [strDate componentsSeparatedByString:@" "];
NSString *str;
str = [arr objectAtIndex:0];
NSLog(@"strdate: %@",str); // strdate: 2011-02-28
NSArray *arr_my = [str componentsSeparatedByString:@"-"];
NSInteger month = [[arr_my objectAtIndex:1] intValue];
NSLog(@"month - 5 %d",month -5);
NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:month -5];
NSLog(@"path = %@",path);
[self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}
The reason that I do month-5 is that my tableview start at the month June. What my problem is, is that it scrolls down to the last row of the section instead of the first. Can anybody help me?
Kind regards,
EDIT
My tableview looks likes this.
---Section 1: June -----
- row 1 (12-06-2012)
- row 2 (14-06-2012)
- row 3 (20-06-2012)
- row 4 (22-06-2012)
---Section 2: July -----
- row 1 (2-07-2012)
- row 2 (14-07-2012)
- row 3 (21-07-2012)
- row 4 (27-07-2012)
---Section 3: August -----
- row 1 (2-08-2012)
- row 2 (14-08-2012)
---Section 4: September -----
- row 1 (17-09-2012)
---Section 5: Oktober -----
- row 1
- row 2
- row 3
- row 4
---Section 6: November -----
- row 1
- row 2
- row 3
- row 4
---Section 7: December -----
- row 1
- row 2
- row 3
---Section 8: January -----
- row 1
- row 2
EDIT: screenshot
Here you can see a screenshot of how my tableview looks after scrolling. Screenshot
A: The problem is, that the section index starts at 0 not at 1.
So when your returned month is 6 your calling:
NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:1]; // month - 5 = 1
[self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
But you should call:
NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:0];
So your scrolling to the section that is 1 below the section you actually wanted to scroll to. That's why it appears as if it would scroll to the last row of the previous section.
Replace month - 5 by month - 6 and it should work as you want.
By the way I would suggest to modify your code to retrieve the current month like this:
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
int month = [[dateFormatter stringFromDate:now] intValue];
//...
| |
doc_23526966
|
import numpy as np
import pandas as pd
import os
import spacy
import csv
from sklearn.preprocessing import LabelEncoder
from sklearn.svm import SVC
# read data from csv
def read_data(path):
with open(path, 'r') as csvfile:
readcsv = csv.reader(csvfile, delimiter=',')
labels = []
sentences = []
for row in readcsv:
label = row[0]
sentence = row[1]
labels.append(label)
sentences.append(sentence)
return sentences, labels
# Loading Test Data
sentences_test, labels_test = read_data('./a_test.csv')
# print out the first two rows
print(sentences_test[:2], '\n')
print(labels_test[:2])
# Loading Training Data
sentences_train, labels_train = read_data('./a_train.csv')
# Load the spacy model: nlp
nlp = spacy.load('en_core_web_lg')
embedding_dim = nlp.vocab.vectors_length
print(embedding_dim)
def encode_sentences(sentences):
# Calculate number of sentences
n_sentences = len(sentences)
print('Length :-', n_sentences)
X = np.zeros((n_sentences, embedding_dim))
# y = np.zeros((n_sentences, embedding_dim))
# Iterate over the sentences
for idx, sentence in enumerate(sentences):
# Pass each sentence to the nlp object to create a document
doc = nlp(sentence)
# Save the document's .vector attribute to the corresponding row in
# X
X[idx, :] = doc.vector
return X
train_X = encode_sentences(sentences_train)
test_X = encode_sentences(sentences_test)
# every label gets his own number
def label_encoding(labels):
# Calculate the length of labels
n_labels = len(labels)
print('Number of labels :-', n_labels)
le = LabelEncoder()
y = le.fit_transform(labels)
print(y[:100])
print('Length of y :- ', y.shape)
return y
train_y = label_encoding(labels_train)
test_y = label_encoding(labels_test)
df1 = pd.read_csv('./a_train.csv', delimiter=',')
df1.dataframeName = 'a_train.csv'
nRow, nCol = df1.shape
print(f'There are {nRow} rows and {nCol} columns')
df1.sample(10)
df1.describe()
# X_train and y_train was given.
def svc_training(X, y):
# Create a support vector classifier
clf = SVC(C=1)
# Fit the classifier using the training data
clf.fit(X, y)
return clf
model = svc_training(train_X, train_y)
print(model.predict(train_X))
# Validation Step
def svc_validation(model, X, y):
# Predict the labels of the test set
y_pred = model.predict(X)
# Count the number of correct predictions
n_correct = 0
for i in range(len(y)):
if y_pred[i] == y[i]:
n_correct += 1
print("Predicted {0} correctly out of {1} training examples".format(n_correct, len(y)))
#svc_validation(model, train_X, train_y)
#svc_validation(model, test_X, test_y)
A: spaCy has methods to write any given model to and from disk.
Go model.to_disk(path) to store the model on your hard drive, then model.from_disk() to retrieve it. Let me know if this answers your question.
A: From what I gather you are trying to save the data so every time you run the program you don't need to calculate it again. The best I can do is suggest you write the data to a dedicated text file to serve as a data dump.
with open("datadump.txt", w) as file:
file.write(train_X)
file.write(train_y)
| |
doc_23526967
|
If I continue and try to run anyway, the WP7 project never starts or sometimes I get "AG_E_PARSER_BAD_TYPE error" and it points to the line in the xaml I used a control from the Silverlight project .
The code between these two projects is about 99% the same. Is there another way to reuse code then what I am trying? Or how can I get this to work?
A: I'm not that familiar with the difference between the two platforms, but you can link the code files into a different project without duplicating them. Add existing item, and click on the down arrow next to the 'Add' or OK button. Choose Link.
A: The typical way of achieving this is by using a pattern like MVVM which will allow you to define a common model and viewmodel layer (perhaps in a separate project) the defining a different view layer that references that common project.
You said it yourself, you will only share MOST of the code, not all of it, so you will, at least at some time, need to create device/front-end specific logic and layout.
A: Rather than add a Silverlight [presumably class library] project to your WP7 app, try creating a WP7 class library and then link the files from the silverlight library. You will still only have one copy of each file but all your libraries will be built appropraitely for the platform they are running on.
This may also help you identify the cause of the problem. The error AG_E_PARSER_BAD_TYPE suggests that you have a type in the XAML in your Silverlight project which isn't supported on the phone.
| |
doc_23526968
|
class SwapClient(object):
def __init__(self, slippage):
self.slippage = slippage
def add_liquidity(self):
print("Add liquidity")
class WaultSwapClient(SwapClient):
def __init__(self, *args, **kwargs):
self.exchange_name = 'waultswap'
super().__init__(self, *args, **kwargs)
class BSCClient:
def __init__(self, testnet, gas_price, gas_buffer, *args, **kwargs):
self.testnet = testnet
self.gas_price = gas_price
self.gas_buffer = gas_buffer
super().__init__(self, *args, **kwargs)
class WaultSwapBSCClient(BSCClient, WaultSwapClient):
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
def claim_(self, pid):
print("Claim rewards")
sc = WaultSwapBSCClient(True, 5, 1, 0.01)
This is the error I'm getting:
TypeError: __init__() takes 2 positional arguments but 5 were given
A: I actually think I fixed it thanks to @user2357112. I removed self from the super calls which made it work.
class SwapClient(object):
def __init__(self, slippage):
self.slippage = slippage
def add_liquidity(self):
print("Add liquidity")
class WaultSwapClient(SwapClient):
def __init__(self, *args, **kwargs):
self.exchange_name = 'waultswap'
super().__init__(*args, **kwargs)
class BSCClient:
def __init__(self, testnet, gas_price, gas_buffer, *args, **kwargs):
self.testnet = testnet
self.gas_price = gas_price
self.gas_buffer = gas_buffer
super().__init__(*args, **kwargs)
class WaultSwapBSCClient(BSCClient, WaultSwapClient):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def claim_(self, pid):
print("Claim rewards")
sc = WaultSwapBSCClient(True, 5, 1, 0.01)
| |
doc_23526969
|
*
*There is an IShell which is nothing but an ordinary console able
to consume somewhat command like do param1=value1 --option.
IShell should orchestrate whole execution. It does not run commands, the only thing it does is starts appropriate
process.
*Any process started from the running IShell instance should be able to report back to it what's happening inside. So,
say, IShell has started process A to do something
complicated; process A should be able to report both progress
and result back to parent IShell. In practice, it means, that
there should be a mechanism how to, for example, print message
from process A to appropriate IShell.
*Finally, code should work both with Windows and Linux.
I really like Haskell and I'd like to promote "real-world" Haskell usage. But I don't know existing libraries well, I haven't done yet any "real-world" Haskell app.
Thus, questions:
How can I establish IShell <- it's processes communication? Is there a single library able to handle both Windows-specific and Linux-specific stuff?
A: The process package supports Linux and Windows and provides mechanisms for communicating with children processes via their stdin, stdout, stderr, and exit code.
The network package supports Linux and Windows and provides mechanisms for communicating with children processes via socket.
| |
doc_23526970
|
My question is if this is the correct way to differentiating the collectionViews for the "override func observeValue"?
Everything looks like its working fine but don't know if this is the correct way to do this and if I will have future issues?
private static var InicioRecetasCollectionViewContext = UnsafeMutableRawPointer.allocate(byteCount: 4 * 4, alignment: 1)
private static var InicioPedidoServerCollectionViewContext = UnsafeMutableRawPointer.allocate(byteCount: 4 * 4, alignment: 1)
//Set the heigh of the table view so it scrolls as one.
override func viewWillAppear(_ animated: Bool) {
self.InicioRecetasCollectionView.addObserver(self, forKeyPath: "contentSize", options: .new, context: InicioViewController.InicioRecetasCollectionViewContext)
self.InicioPedidoServerCollectionView.addObserver(self, forKeyPath: "contentSize", options: .new, context: InicioViewController.InicioPedidoServerCollectionViewContext)
}
override func viewWillDisappear(_ animated: Bool) {
self.InicioRecetasCollectionView.removeObserver(self, forKeyPath: "contentSize")
self.InicioPedidoServerCollectionView.removeObserver(self, forKeyPath: "contentSize")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("contentSize")
if keyPath == "contentSize" {
if let newValue = change?[.newKey]{
let newSize = newValue as! CGSize
if(context == InicioViewController.InicioRecetasCollectionViewContext){
self.InicioProveedorAvisosCollectionViewHeightConstraint.constant = newSize.height
}
if(context == InicioViewController.InicioPedidoServerCollectionViewContext){
self.InicioPedidoServerCollectionViewHeightConstraint.constant = newSize.height
}
}
}
}
| |
doc_23526971
|
In the same class I have a @Scheduled method, and I wish to set the cron expression to the bean's property.
I tried this already and it doesn't work
@Scheduled(cron = "#{propertyBean.cronExpression}")
Any ideas?
Thank you.
A: This annotation worked for me:
@Scheduled(cron = "${property.with.cron}")
With this in our spring profile/application.properties:
property.with.cron=*/10 * * * * *
We're using spring boot just fyi
| |
doc_23526972
|
Any idea ??
import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
hostname='hello'
sender = 'xx@xx.com'
receivers = ['vholla@xx.com']
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receivers
msg['Subject'] = "Upgrade started for"+hostname+"."
try:
smtpObj = smtplib.SMTP('mail.xxx.com',25)
smtpObj.sendmail(sender, receivers, msg.as_string())
print "Successfully sent email"
except:
print "Error: unable to send email"
A: I have this option works by postfix:
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP()
s.connect('localhost') # connect to the SMTP server
doc = "<html><h1>Test title</h1></html>"
while True:
msg = MIMEText( doc, _subtype='html', _charset='utf-8' )
s.sendmail('xx@xx.com', ['vholla@xx.com'], msg.as_string())
s.quit()
| |
doc_23526973
|
I did change my Build Action on the AndroidManifest.xml.
I did change my file locations to not include symbols or spaces.
Attached is what the output looks like now and does nothing afterwards.
Also, at the bottom of my screen which I excluded says - "Conecting to logcat: Samsung SM-N9005..." and nothing happens.
A: Use adb to uninstall the ghost of your app
adb uninstall my.package.id
Reference:
Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed
A: Usually this happens when you mix between RELEASE and DEBUG versions. You cannot update a DEBUG version with a RELEASE one and vice versa.
If you do not see your app in the applications list it's because after the failing of the UPDATE it's named with the package name, and maybe the position is different than usual.
A: Same thing happened to my previously build and checked code. What worked for me is from the emulator drop down in visual studio change to some different platform tablet if phone is selected or phone if tablet is selected.
| |
doc_23526974
|
example :
int var1,var2,var3;
int result;
var1 = 1;
var2 = 2;
var3 = 3;
result = ........??;
printf("Result %d",result);
output :
123
How can I do this?
A: result = var1 * 100 + var2 *10 + var3;
A: printf("Result %d%d%d",var1, var2, var3);
A: Yay, C++11 variadic templates are awesome! Here's a N-finitely expandable version, assuming sum(args) < INT_MAX
template<int max, int ...arguments>
int merge_integers()
{
int args[] = { arguments... };
int size = sizeof(args) / sizeof(int);
int mul = 1;
int result = 0;
for (int i = size; i--; )
{
result += args[i] * mul;
mul *= max;
}
return result;
}
Example usage:
printf("%d\n", merge_integers<10, 5, 4, 3, 2, 1>());
printf("%x\n", merge_integers<16, 0xA, 0xB, 0x1, 0x3, 0x5>());
printf("%o\n", merge_integers<8, 1, 2, 3, 4, 7>());
Output:
54321
ab135
12347
A: Should it be:
char str[100];
sprintf(str, "%d%d%d", var1, var2, var3);
sscanf(str, "%d", &result); // or atoi
A: If you do not know how many digits do the vars have you will have to go through stringstream:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int a = 10;
int b = 12;
int c = 2;
stringstream ss;
ss << a << b << c;
int merge;
ss >> merge;
cout << merge << endl;
return 0;
}
Working example on ideone.
A: Do you really need int variables ? Does string meet you requirements ?
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int
main()
{
int var1 = 1;
int var2 = 2;
int var3 = 3;
ostringstream oss;
string result;
oss<<var1<<var2<<var3;
result = oss.str();
cout<<result<<endl;
return 0;
}
| |
doc_23526975
|
def foo(file):
'''
Function will read the file contents and output a boolean value based on its contents
'''
# Code to read file here...
return bool
rule check_input:
input: "input.txt"
run:
bool = foo("input.txt")
rule bool_is_True:
input: "input.txt"
output: "out1.txt"
run:
# Some code to generate out1.txt. This rule is supposed to run only if foo("input.txt") is true
rule bool_is_False:
input: "input.txt"
output: "out2.txt"
run:
# Some code to generate out2.txt. This rule is supposed to run only if foo("input.txt") is False
How do I write my rules to handle this situation? Also how do I write my first rule all if the output files are unknown before the rule check_input is executed?
Thanks!
A: You're right, snakemake has to know which files to produce before executing the rules. Therefore, I suggest you use a function which reads what you called "the input file" and define the output of the workflow accordingly.
ex:
def getTargetsFromInput():
targets = list()
## read file and add target files to targets
return targets
rule all:
input: getTargetsFromInput()
...
You can define the path of the input file with --config argument on the snakemake command line or directly use some sort of structured input file (yaml, json) and use the keyword configfile: in the Snakefile: https://snakemake.readthedocs.io/en/stable/snakefiles/configuration.html
A: Thanks Eric. I got it work with:
def getTargetsFromInput(file):
with open(file) as f:
line = f.readline()
if line.strip() == "out1":
return "out1.txt"
else:
return "out2.txt"
rule all:
input: getTargetsFromInput("input.txt")
rule out1:
input: "input.txt"
output: "out1.txt"
run: shell("echo 'out1' > out1.txt")
rule out2:
input: "input.txt"
output: "out2.txt"
run: shell("echo 'out2' > out2.txt")
| |
doc_23526976
|
to populate this:
<input id="date" value="" type="textbox" />
I would like to trigger a jquery event after a date is selected, but am unsure of how to call this, i know that i can do things like keyup, click, etc. but is there a way to do this if a value is selected from the widget?
Thanks.
A: Directly from the docs (under the events tab):
$('.selector').datepicker({
onSelect: function(dateText, inst) {
// Put your code here
}
});
A: Try this...
$('#date').datepicker({
onSelect: function(dateText, uiInstance) {
// Do stuff with it
}
});
A: datepicker has a callback function you can use initiate some functionality after a date is selected.
$('.selector').datepicker({
onSelect: function(dateText, inst) { ... }
});
| |
doc_23526977
|
{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined )
{
alert("In undefined");
}
alert("end");
}
When the if statement is false, it never gets to alert("end") ? When it is true, it executes properly. Why?
A: There is probably a null pointer exception and you do not have errors outputting to your browser.
You need some output to check:
alert(document);
alert(document.dd);
alert(document.dd.begin);
alert(document.dd.begin.checked);
alert(document.dd.end);
alert(document.dd.end.checked);
If you get undefined from any of those, then your code will not execute properly.
Edit: Also, the other answers here all have good information. Read those as well.
Edit2: Alternative - Surround your code in a try/catch block and alert the error:
function valid(){
try{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined ){
alert("In undefined");
}
alert("end");
} catch (e) {
alert(e);
}
}
A: Are there any errors in your browsers error console? I'm guessing it's because it's trying to evaluate a property that doesn't exist, this causing it to fail (never getting to the == undefined). You can just check that the property exists or use the typeof to check if it's undefined.
if (!document.dd.begin.checked.length || !document.dd.end.checked.length)
{
alert("In undefined");
}
if (typeof document.dd.begin.checked.length == 'undefined' || typeof document.dd.end.checked.length == 'undefined' )
{
alert("In undefined");
}
A: http://getfirebug.com/
| |
doc_23526978
|
quotes =[{'Offer_Title': 'New credit ', 'Offer Details': 'The Centre'},
{'Offer_Title': 'New credit1 ', 'Offer Details': 'The Centre1'}]
#If I flatten the list as below:
flat_list = [item for sublist in quotes for item in sublist]
How do I then ensure values corressponding to Offer_Title and Offer Details get loaded into separate columns?
params = ['?' for item in flat_list]
sql = 'INSERT INTO comp_offer_records (Offer_Title, Offer_Details) VALUES (%s, %s);' % ','.join(params)
mycursor.executemany(sql, flat_list)
However this gives error:
sql = 'INSERT INTO comp_offer_records (Offer_Title, Offer_Details) VALUES (%s, %s);' % ','.join(params)
TypeError: not enough arguments for format string
A: '(%s, %s);' % ','.join(params)
Expected 2 string arguments, when you passed 1
Replace it with
'(%s, %s);' % params
| |
doc_23526979
|
But i am facing problems in catching unexpected errors like "NullPointerException" in constructor or error Codes 500, 400 etc.
i used the tags in the "web.xml"
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/sc00/ErrorPage.jsp</location>
</error-page>
I tried many ways to handle the exceptions, can any one help me in finding out a solution. The error i am getting when i try to handle these exceptions is as follows.
I am using JSF 1.2 and the server is websphere 8
The Console shows the Following Exception.
com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0014E: Uncaught service() exception root cause Faces Servlet: javax.servlet.ServletException
E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: An exception was thrown by one of the service methods of the servlet [/sc00/ErrorPage.jsp] in application [MembershipEligibilityScreensEAR]. Exception created : [java.lang.RuntimeException: FacesContext not found
My Error Page is in /WebContent/sc00/ErrorPage.jsp, ErrorPage.jsp has no backing bean associated with it.
Many solutions asked me to look at the URL path of Faces Servlet, In My web.xml the servlet-mapping is a follows
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
all the paths in my faces-config.xml refer to /FolderName/JspName and they work fine and they work fine even in Navigation.xml.
How can i navigate it to ErrorPage.jsp, Is there any way so that i can write a listener to this kind of problem
Sorry for posting too many redundant questions, i am new to JSF and i don't know the rules of StackOverflow, I apologize for the problem i have caused.
any solution would be appreciated.
A: java.lang.RuntimeException: FacesContext not found
That will happen when you're requesting a JSP page containing JSF components through an URL which doesn't match the URL pattern of the FacesServlet (who is the one responsible for creating the FacesContext).
You need to change the error page location to match the URL pattern of the FacesServlet as definited in web.xml. Based on your duplicate questions on the subject, this is among others *.faces, so setting the error page location as follows should do, exactly as I suggested in a comment on your first question on the subject.
<location>/sc00/ErrorPage.faces</location>
| |
doc_23526980
|
I originally intended to simply generate 1 character per byte needed, but apparently characters aren't all a byte anymore.
Any help is appreciated!
A: I recommend using RNGCryptoServiceProvider it may generate as many random bytes as you want. You can then convert it to string (e.g. using byte64 encoding or other method).
Remember to add using System.Security.Cryptography; to the file.
public class RandomService : IDisposable
{
private readonly RNGCryptoServiceProvider rngCsp;
public CryptoService()
{
rngCsp = new RNGCryptoServiceProvider();
}
public byte[] GetRandomBytes(int length)
{
var bytes = new byte[length];
rngCsp.GetBytes(bytes);
return bytes;
}
public string GetRandomString(int length)
{
var numberOfBytesForBase64 = (int) Math.Ceiling((length*3)/4.0);
string base64String = Convert.ToBase64String(GetRandomBytes(numberOfBytesForBase64)).Substring(0, length); //might be longer because of padding
return base64String.Replace('+', '_').Replace('/', '-'); //we don't like these base64 characters
}
public void Dispose()
{
rngCsp.Dispose();
}
}
A: You could probably take the Random class, convert to byte[] and then ToString()
A: char[] UsableChars = { 'a', 'b', 'c', '1', ...., `☺` };
Random r = new Random();
int wantedSize = 12;
string s = new string (Enumerable.Range(0, wantedSize)
.Select((i) => UsableChars[r.Next(UsableChars.Length)]).ToArray());
A: If you use a limited set of characters, you can pick those that will end up as single byte codes regardless of the encoding used.
public byte[] CreateFiller(int length, Random rnd) {
string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return Encoding.UTF8.GetBytes(Enumerable.Range(0, length).Select(i => chars[rnd.Next(chars.Length)]).ToArray());
}
// only use the overload that creates a Random object itself if you use it once, not in a loop
public byte[] CreateFiller(int length) {
return CreateFiller(length, new Random());
}
| |
doc_23526981
|
The link to the table is below.
I'm wanting to make the Genre and Age Rating drop down menus like the Release Date column. I'm struggling to code it correctly, as when I copy the other code I already have and attach it to the Genre columns then the Javascript stops working completely.
HTML:
<table>
<thead>
<tr>
<th>Video Game</th>
<th>Release Date</th>
<th>Genre</th>
<th>Age Rating</th>
</tr>
</thead>
<tbody>
<tr>
<td>Game 1</td>
<td>
<ul>
<li>11th June</li>
</ul>
</td>
<td>
<ul>
<li>Sport</li>
</ul>
</td>
<td>
<ul>
<li>16</li>
</ul>
</td>
</tr>
<tr>
<td>Game 2 </td>
<td>
<ul>
<li>11th July</li>
</ul>
</td>
<td>
<ul>
<li>Sci-Fi</li>
</ul>
</td>
<td>
<ul>
<li>18</li>
</ul>
</td>
</tr>
</tbody>
</table>
Javascript:
$(function () {
$('table').tablesorter({
theme: 'blue',
widgets: ['filter'],
widgetOptions: {
filter_functions: {
1: {
"January": function (e, n) {
return /January/.test(n);
},
"February": function (e, n) {
return /February/.test(n);
},
"March": function (e, n) {
return /March/.test(n);
},
"April": function (e, n) {
return /April/.test(n);
},
"May": function (e, n) {
return /May/.test(n);
},
"June": function (e, n) {
return /June/.test(n);
},
"July": function (e, n) {
return /July/.test(n);
},
"August": function (e, n) {
return /August/.test(n);
},
"September": function (e, n) {
return /September/.test(n);
},
"October": function (e, n) {
return /October/.test(n);
},
"November": function (e, n) {
return /November/.test(n);
},
"December": function (e, n) {
return /December/.test(n);
}
}
}
}
});
});
Visit the JSFiddle
A: You have to add additonal filter functions:
filter_functions: {
1: {
"January": function (e, n) {
return /January/.test(n);
},
"February": function (e, n) {
return /February/.test(n);
},
// other months
},
2: {
"Sport": function (e, n) {
return /Sport/.test(n);
},
"Sci-Fi": function (e, n) {
return /Sci-Fi/.test(n);
}
},
3: {
"16": function (e, n) {
return /16/.test(n);
},
"18": function (e, n) {
return /18/.test(n);
}
}
}
It will create dropdown menus under Genre with the options Sport and Sci-Fi and another one under Age Rating with the options 16 and 18. Is that what you're looking for?
| |
doc_23526982
|
I wanted this to be repeatable and easy to use so I made a metaclass for it. This works like a charm.
The problem is that when using Sphinx to generate documentation properties don't get documented. Everything else is documented as expected. I have no idea how to fix this, maybe this is a problem with Sphinx?
The module:
import sys
import types
class ClassAsModule(type):
def __new__(cls, name, bases, attrs):
# Make sure the name of the class is the module name.
name = attrs.pop('__module__')
# Create a class.
cls = type.__new__(cls, name, bases, attrs)
# Instantiate the class and register it.
sys.modules[name] = cls = cls(name)
# Update the dict so dir works properly
cls.__dict__.update(attrs)
class TestClass(types.ModuleType):
"""TestClass docstring."""
__metaclass__ = ClassAsModule
@property
def some_property(self):
"""Property docstring."""
pass
def meth():
"""meth doc"""
pass
And a copy-paste to generate/view Sphinx documentation:
sphinx-apidoc . -o doc --full
sphinx-build doc html
xdg-open html/module.html
The most essential part is to document the class' properties. Bonus points to also document original module members.
EDIT: The class should be documented as the module it is in. The class is used this way and should thus appear this way in Sphinx.
Example of desired output:
Module Foo
TestClass docstring.
some_property
Property docstring.
meth()
meth doc
EDIT 2: I found something that may aid in finding a solution. When having a regular module foo with the following content:
#: Property of foo
prop = 'test'
Sphinx documents this like:
foo.prop = 'test'
Property of foo
The same works if prop is an attribute of a class. I haven't figured out why it doesn't work in my special case.
A: Here's my understanding.
The theory is: making a mutant your class act like a module this (a bit hacky) way makes sphinx think that he doesn't need (to parse) properties from modules (because it's a class-level paradigm). So, for sphinx, TestClass is a module.
First of all, to make sure that the culprit is the code for making a class act like a module - let's remove it:
class ClassAsModule(type):
pass
we'll see in docs:
package Package
script Module
class package.script.ClassAsModule
Bases: type
class package.script.TestClass
Bases: module
TestClass docstring.
meth()
meth doc
some_property
Property docstring.
As you see, sphinx read the property without any problems. Nothing special here.
Possible solution for your problem is to avoid using @property decorator and replace it with calling property class constructor. E.g.:
import sys
import types
class ClassAsModule(type):
def __new__(cls, name, bases, attrs):
# Make sure the name of the class is the module name.
name = attrs.pop('__module__')
# Create a class.
cls = type.__new__(cls, name, bases, attrs)
# Instantiate the class and register it.
sys.modules[name] = cls = cls(name)
# Update the dict so dir works properly
cls.__dict__.update(attrs)
class TestClass(types.ModuleType):
"""TestClass docstring."""
__metaclass__ = ClassAsModule
def get_some_property(self):
"""Property docstring."""
pass
some_property = property(get_some_property)
def meth(self):
"""meth doc"""
pass
For this code sphinx generates:
package Package
script Module
TestClass docstring.
package.script.get_some_property(self)
Property docstring.
package.script.meth(self)
meth doc
May be the answer is a piece of nonsense, but I hope it'll point you to the right direction.
A: The way I've found that works best is to keep the file contents the same as if you were writing a regular module, then at the end replace the embryonic module in sys.modules:
"""Module docstring. """
import sys
import types
def _some_property(self):
pass
some_property = property(_some_property)
"""Property docstring."""
def meth():
"""meth doc"""
pass
def _make_class_module(name):
mod = sys.modules[name]
cls = type('ClassModule', (types.ModuleType,), mod.__dict__)
clsmod = cls(name)
clsmod.__dict__.update(mod.__dict__)
clsmod.__wrapped__ = mod
sys.modules[name] = clsmod
_make_class_module(__name__)
Text documentation:
mymod Module
************
Module docstring.
mymod.meth()
meth doc
mymod.some_property = None
Property docstring.
For the version of Sphinx I'm using (v1.1.3), it looks like you have to apply the property constructor explicitly (you can't use it as a decorator), and the docstring has to go in the file at the top level, on the line after the constructor call that creates the property (it doesn't work as a docstring inside the property getter). The source is still fairly readable, though.
| |
doc_23526983
|
public void a(String a) {
if (a == null) {
throw new IllegalArgumentException();
}
}
public void b(Queue<Integer> b) {
if (b == null) {
throw new IllegalArgumentException();
}
}
public void c(Stack<Integer> c) {
if (c == null) {
throw new IllegalArgumentException();
}
}
Is it possible to write a method that do the throw new exception job
? That is something like this:
public void a(String a) {
check(a);
}
public void b(Queue<Integer> b) {
check(b);
}
public void c(Stack<Integer> c) {
check(c);
}
Notice that their types of parameter is not the same.
A: you can be more generic like:
public void check(Object a) {
if (a == null) {
throw new IllegalArgumentException();
}
}
A: public static <X extends Throwable, T> T ifNullThrow(final T value, @NonNull final Supplier<? extends X> exceptionSupplier)
throws X {
if (value != null) {
return value;
}
throw exceptionSupplier.get();
}
| |
doc_23526984
|
*
*newsletter.php, and
*n-feedburner.php
Let me first tell you what is the code written in n-feedburner.php→
The relevant code in the newsletter.php looks like this →
if($newsletter_provider == 'feedburner')
{
locate_template('inc/widgets/newsletter/n-feedburner.php',true,false);
}
But when we have this arrangement the Feedburner subscription system doesn't work.
However,
when we use this arrangement →
then things start to work.
Reason I find is:
<?php echo $feedburner_id; ?> doesnt work alone in n-feedburner.php
$feedburner_id: this is declared in newsletter.php so it is not available in n-feedburner.php
what is the solution? I want to keep the files separate because as API's will increases such as MailChimp, constant contact it will be important to keep the code clean.
A: try the following, which will retrieve the file and include it.
require( locate_template('inc/widgets/newsletter/n-feedburner.php', false) ) ;
also you can pass variable to n-feedburner.php using Global variable or any similar methods.
| |
doc_23526985
|
I have confusion about the this point:
Apps that contain empty iAd banners will be rejected
Does this mean that I cannot have iAds and In-App purchase to remove the iAds from my App for upgrading from Lite version to Pro version?
Can anybody suggest how to handle this situation where i have Lite version and Pro version?? Do I need to have 2 apps in App Store?
A: This particular point refers to showing iAd banners when they haven't loaded yet. iAd banners should be hidden until content has arrived. If you show an ad banner when there is no content, you may get a review rejection worded similar to this:
We've completed the review of your application; however, we cannot post this version to the App Store because it displays an empty iAd banner when ad content is not available. The banner within the app should be hidden whenever ad content is not being served by iAd. We have included additional details below to help explain the issue. We hope that you'll consider revising and resubmitting your application.
To handle the case where ad content is not available, you will need to implement a banner view delegate. An example code snippet is included here for your convenience. Additionally, you may wish to review the section "Working with Banner Views" of the iAd Programming Guide for specific details: https://developer.apple.com/iphone/prerelease/library/documentation/UserExperience/Conceptual/iAd_Guide/WorkingwithBannerViews/WorkingwithBannerViews.html
The ADBannerView will call bannerViewDidLoadAd: on its delegate. This is your cue to show the ad banner. The banner should not be shown until there is an ad loaded.
To answer your last question, you can have a separate Lite and Pro version without any problems. Or, you can go 'freemium' where you have a single application and the user does an IAP to remove the ads.
A: Yes, you are allowed to show Ads (iAd or anyone else') and turn them off if the user makes an In-Ap Purchase. There are no Terms of Service that disallow that.
One simplistic implementation would be to check a value saved in NSUserDefaults. If the value is NOT there show Ads, and if the value IS there do not. You set that value when the user makes the In-App purchase.
A: Answer to my Question is YES. Finally I have my app on AppStore: https://itunes.apple.com/in/app/ui-maker-design-mobile-app/id791072042?mt=8
It does allows to have In-app purchase to make iAds Free version. Thanks to Apple.... :)
Here both answers are correct.. But unfortunately, I can accept only one... so +1 to both... :)
| |
doc_23526986
|
On login on the mobile, after the 'two-step' login with simple permission and then ask for more, I ultimately have these permissions:
user_friends
user_posts
manage_pages
publish_pages
publish_actions
public_profile
For a (test) user of the app, that has not yet logged into the app and has therefore not yet granted any permissions, when I query
/v2.3/{user-id}/feed or /v2.3/{user-id}/posts
I get a "200" (non-error) JSON response with no data, from memory its something like this:
{
"data" : [
]
}
which agrees with the documentation as given in FB docs
where it says:
If you attempt to read data from a feed that your app has not been authorized to access, the call will return an empty array. OK, so all that makes sense.
So then I get a list of messages from a friend (test user at this point) and store their message ids, it looks like they are in the form: userid_postid and I can scan the text, great. I use API v2.3 which looks like it will close in July 2017, but it works now.
OK, so now I want to post to the users wall or page or something that FB calls it - is it true that I can't do this anymore? I next tried to post to the comments of the stored user_postid but this fails with:
{HttpStatus: 403, errorCode: 200, errorType: OAuthException, errorMessage: (#200) Permissions error}
I do think I should have the permission to do this. I do notice that there is no comment widget on the test users posts - is that the problem? Do some posts not have comments at all, or is this a function of test users only? Here is what the posts look like, note there is no comment line shown:
I've come a long way, and can do quite a bit (get posts, user pics, friends that use the app - despite FB's documentation) but am now stuck. Any help or pointers greatly appreciated.
EDIT, forgot the code for the attempted publish to a comment:
params.putString("message", someText);
new GraphRequest(
// version 2.3 will work until July 8, 2017
AccessToken.getCurrentAccessToken(),
"/v2.3/" + mFacebookPostId + "/comments",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
mSends++;
FacebookRequestError err = response.getError();
if (err == null || err.getErrorCode() == 0) {
mSendGood++;
}
tv_status.setText("Sent " + mSends + " posts, " + mSendGood + " good");
}
}
).executeAsync();
Update: am I supposed to get a 'page access token', again the FB docs are not clear?
A: The answer seems to be a bug with the Facebook Test Users. I was never sure if I could do what I wanted to do as this was a first FB development for me, but started to get suspicious when I saw that Test User's posts do not have comments or like buttons.
But now I am not sure how to test this code, as real users can't use the app in development mode?
| |
doc_23526987
|
Login failed for user 'FrienDev'.
Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.
Exception Details:
System.Data.SqlClient.SqlException:
Login failed for user 'FrienDev'.
Stack Trace:
[SqlException (0x80131904): Login failed for user 'FrienDev'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4849719
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +35
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +144
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +342
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +221
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +433
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user) +44
System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe() +45
System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode() +20
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +57
System.Data.Linq.DataQuery1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +35
System.Linq.Enumerable.SingleOrDefault(IEnumerable1 source) +221
FrienDev.BusinessRules.UserRules.GetCurrentUser() +594
FrienDev.BusinessRules.UserRules.UpdateUserLoginInfomation() +66
FrienDev.BusinessRules.OnlineRules.UserLogin(String userId) +115
HandlerPage.Page_Load(Object sender, EventArgs e) in d:\TEST\FrienDevApps\FrienDevWeb\webauth-handler.aspx.cs:89
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Anybody has any clue to that?
Please help!
A: What are you trying to do? What code instruction give you this error? Can you post your code?
Without other info I think you don't have permission to connect to the database. Check your connectionstring and user credentials.
| |
doc_23526988
|
model.objects.filter(last_date__gte=datetime.now()-timedelta(days=F('interval')))
is a no-go, as a F() expression cannot be passed into a timedelta
A little digging, and I discovered DateModifierNode - though it seems it was removed in this commit: https://github.com/django/django/commit/cbb5cdd155668ba771cad6b975676d3b20fed37b (from this now-outdated SO question Django: Using F arguments in datetime.timedelta inside a query)
the commit mentions:
The .dates() queries were implemented by using custom Query, QuerySet,
and Compiler classes. Instead implement them by using expressions and
database converters APIs.
which sounds sensible, and like there should still be a quick easy way - but I've been fruitlessly looking for how to do that for a little too long - anyone know the answer?
A: Ah, answer from the docs: https://docs.djangoproject.com/en/1.9/ref/models/expressions/#using-f-with-annotations
from django.db.models import DateTimeField, ExpressionWrapper, F
Ticket.objects.annotate(
expires=ExpressionWrapper(
F('active_at') + F('duration'), output_field=DateTimeField()))
which should make my original query look like
model.objects.annotate(new_date=ExpressionWrapper(F('last_date') + F('interval'), output_field=DateTimeField())).filter(new_date__gte=datetime.now())
A: In Django 1.10 there's simpler method to do it but you need to change the model a little: use a DurationField. My model is as follows:
class MyModel(models.Model):
timeout = models.DurationField(default=86400 * 7) # default: week
last = models.DateTimeField(auto_now_add=True)
and the query to find objects where last was before now minus timeout is:
MyModel.objects.filter(last__lt=datetime.datetime.now()-F('timeout'))
| |
doc_23526989
|
char = input()
ordchar = ord(char)
nextletter = ordchar + 1
nextletter = chr(nextletter)
if nextletter == ("["):
print("A")
if nextletter == ("{"):
print("a")
if nextletter!=("[","{"):
print(nextletter)
Now, I do see the problem with the code, though I don't know how to rectify it. Basically, on the second to last line of code, I want it to essentially say "if nextletter does not equal { or [ print nextletter".
A: if nextletter not in ["[", "{"]:
print(nextletter)
A: You do not need to test for those characters at all. In the code before it you make sure that nextletter is never going to be either [ or {, if you just assign a different letter to nextletter there:
if nextletter == "[":
nextletter = "A"
elif nextletter == "{":
nextletter = 'a'
If you still need to make such a test, use the not in operator:
if nextletter not in '[{':
not in returns True if the left-hand operand is not present in the sequence on the right. I used a string with two characters in my example, which counts as a sequence:
>>> '[' in '[{'
True
>>> '0' in '[{':
False
A: Use not in membership operator:
if nextletter not in ("[","{"):
print(nextletter)
Also note that, you can avoid the third test if you used if-elif construct rather than individual if's. That way, you can just put the 3rd part in an else block.
A: While the other answers are correct, the right way of doing what you want is using elifand else:
if nextletter == ("[") :
print("A")
elif nextletter == ("{") :
print("a")
else :
print(nextletter)
A: The problem is that you are asking if nextletter is not equal to the tuple of ("[","{"). You wanted to ask if it is not equal to either "[" or "{". Therefore, you must ask,
if nextletter != "[" and nextletter != "{"
This will check if it is neither "[" nor "{". Hope this helps
| |
doc_23526990
|
A: Read the docs:
var minDate = $( ".selector" ).datepicker( "option", "minDate" );
http://jqueryui.com/demos/datepicker/#option-minDate
Updated link on 05, Nov 2018:
http://api.jqueryui.com/datepicker/#option-minDate
| |
doc_23526991
|
abc1-xyz
abc1-ertxyz
abc1xyz
postxyz
abc1
I would like to match everything that starts with "abc1" AND also contains the letters "xyz" somewhere.
I know that I can start with:
/^abc1/
but I am not sure how to combine so it can also match to contain "xyz".
Thank you for your assistance in advance.
A: You should tell us with which language you are coding, regex engines are not always the same.
There is another ambiguous point : Do you need your string to CONTAIN xyz or to END WITH?
Considering you are coding on Javascript..
If you want it to contain xyz, try :
/^abc1.*xyz/
If you want it to end with xyz, try :
/^abc1.*xyz$/
| |
doc_23526992
|
I have a train_df that looks like this:
x y1 y2 y3 y4
0 -20.0 -0.702864 10.392012 1.013891 -8794.9050
1 -19.9 -0.591605 9.450884 1.231116 -8667.2340
2 -19.8 -0.983952 10.240055 0.675153 -8541.5720
And an ideal_df that looks like this:
x y1 y2 ... y48 y49 y50
0 -20.0 -0.912945 0.408082 ... -0.186278 0.912945 0.396850
1 -19.9 -0.867644 0.497186 ... -0.215690 0.867644 0.476954
2 -19.8 -0.813674 0.581322 ... -0.236503 0.813674 0.549129
Both have 400 rows.
I want to to sum up the squared deviation (distance) between y-values of train_df and ideal_df at each given x-value, e.g.:
For the 1st value of x, y1 from train_df and y1 from ideal_df, then y1 from train_df and y2 from ideal_df, etc.
Then repeat the same for every one of the 400 rows of y1 from train_df.
After that, repeat it for y2, y3, and y4 of train_df, but that is the easy part.
I wrote this
squared_deviations_y1_train = (((train_df.y1)-(ideal_df.loc[:,"y1":"y50"])) ** 2).sum()
But I have no idea what I'm doing to be honest.
A: Merge/join the the two dataframes by index and then for each yx column of train_df, compute the squared deviation:
train_df = pd.DataFrame(data=[ [-20.0,-0.702864,10.392012,1.013891,-8794.9050], [-19.9,-0.591605,9.450884,1.231116,-8667.2340], [-19.8,-0.983952,10.240055,0.675153,-8541.5720] ], columns=["x","y1","y2","y3","y4"])
ideal_df = pd.DataFrame(data=[ [-20.0,-0.912945,0.408082,-0.186278,0.912945,0.396850], [-19.9,-0.867644,0.497186,-0.215690,0.867644,0.476954], [-19.8,-0.813674,0.581322,-0.236503,0.813674,0.549129] ], columns=["x","y1","y2","y48","y49","y50"])
ideal_df = ideal_df.add_suffix("_i")
result_df = train_df.merge(ideal_df, left_index=True, right_index=True, how="left")
for t_col in train_df.columns:
if t_col != "x":
result_df[f"{t_col}_sd"] = sum([(result_df[t_col] - result_df[i_col]) ** 2 for i_col in ideal_df.columns if i_col != "x_i"])
[Output]:
x y1 y2 y3 y4 x_i y1_i y2_i y48_i y49_i y50_i y1_sd y2_sd y3_sd y4_sd
0 -20.0 -0.702864 10.392012 1.013891 -8794.905 -20.0 -0.912945 0.408082 -0.186278 0.912945 0.396850 5.365406 529.137105 5.911037 3.867627e+08
1 -19.9 -0.591605 9.450884 1.231116 -8667.234 -19.9 -0.867644 0.497186 -0.215690 0.867644 0.476954 4.674201 434.286809 7.737567 3.756179e+08
2 -19.8 -0.983952 10.240055 0.675153 -8541.572 -19.8 -0.813674 0.581322 -0.236503 0.813674 0.549129 8.619554 508.005021 3.091597 3.648075e+08
| |
doc_23526993
|
However, the OUTPUT value in @select_statement is returned as NULL. I want the @select_statement variable to return the output string. I'm not sure where to put the @select_statementOUT so that it fetches me the string.
This is the code:
ALTER PROCEDURE dbo.selectTableAttributes
@database_name Nvarchar(255),
@schema_name Nvarchar(255),
@table_name Nvarchar(255),
@select_statement nvarchar(MAX) OUT
AS
BEGIN
DECLARE @query1 nvarchar(MAX), @query2 nvarchar(MAX),
@query3 nvarchar(MAX), @query4 nvarchar(MAX),
@querydb nvarchar(MAX), @query nvarchar(MAX)
SET @querydb = N'USE ' + @database_name
I tried assigning @select_statementOUT below which is throwing an error - Incorrect syntax near 'sql_statement' & Incorrect syntax near 'tbl_custom_data'
SET @query1 = N' Select @select_statementOUT =
concat(''select case when count(*) > 100 then ''''transaction'''' else ''''reference'''' end as cloud_content_type, min('',
case when cloud_transaction_column is not null then cloud_transaction_column
else ''1'' end,'') as cloud_transaction_start_date,'',
char(39),
case when cloud_transaction_column is not null then cloud_transaction_column
else ''1'' end,
char(39),
'' as cloud_transaction_column,'',
char(39),
cloud_load_type,
char(39),
'' as cloud_load_type,'',
char(39),
table_type,
char(39),
''as table_type '',
'' from '', tbl_details) sql_statement '
SET @query2 = N'From (Select
tbl_details,
cloud_transaction_column,
case ............ continued .....................................
where col.table_name=''' + @table_name
SET @query3 = N'''
and col.TABLE_SCHEMA=''' + @schema_name
SET @query4 = N'''
) tbl_columns
where cloud_transaction_seq is not null
group by tbl_details)
Tbl_col_group
) tbl_final_data
) tbl_custom_data'
SET @query = @querydb + @query1 + @query2 + @query3 + @query4
EXEC sp_executesql @query, N'@database_name Nvarchar(255),
@schema_name Nvarchar(255),
@table_name Nvarchar(255),
@select_statementOUT nvarchar(MAX) OUTPUT',
@database_name, @schema_name,
@table_name,
@select_statementOUT = @select_statement OUTPUT
END
| |
doc_23526994
|
The test should relay on a metastore that is stored on the local disk (as explained in the programming guide)
I define the session in the following way:
val spark = SparkSession
.builder
.config(conf)
.enableHiveSupport()
.getOrCreate()
the creation of the spark session fails with the error:
org.datanucleus.exceptions.NucleusUserException: Persistence process has been specified to use a ClassLoaderResolver of name "datanucleus" yet this has not been found by the DataNucleus plugin mechanism. Please check your CLASSPATH and plugin specification.
I managed to work around this error by adding the following dependency:
"org.datanucleus" % "datanucleus-accessplatform-jdo-rdbms" % "3.2.9"
This is strange to me, since this library is already included in spark.
Is there another way to solve this?
I wouldn't wan't to keep track of the library and update it with every new spark version.
| |
doc_23526995
|
Get: async function (request, cancelToken = null) {
console.info('Sending GET', request)
store.commit('global/setLoader', true)
let headers = getAuthTokenHeader()
try {
var res = await Vue.axios({
url: baseUrl + request.Url,
params: request.Params,
method: 'GET',
headers
}).catch(function (error) {
console.error('Failed to GET: ' + error)
if (typeof error.response !== 'undefined' && typeof error.response.data !== 'undefined' && error.response.data !== null) {
throw new Error(error.response.data)
} else {
throw error
}
})
console.info('Request received', res)
return res
} finally {
store.commit('global/setLoader', false)
}
},
The error is thrown on the line if (typeof error.response !== 'undefined' && typeof error.response.data !== 'undefined' && error.response.data !== null) {
According to https://javascript.info/async-await#error-handling
I should not be receiving this "Ucaught (in promise)" error since I am wrapping the whole asynchronous call in an await.
The calling code is also awaiting this code. Here is the call for reference.
static async GetPackagingDimensions (input, Id) {
const request = {
Url: 'api/packing/getPackagingBoxDimensionsByBarCode',
Params: {
boxBarcode: input,
orderId: Id
}
}
const res = await HttpUtil.Get(request)
return res
}
Interesting enough, if I wrap the calling code itself in a try catch, the error is caught appropriately.
Why am I not able to catch the rejected promise from within my catch?
Quick Edit
- My console.log is also not being called inside the catch, and yet the error seems to be thrown on the following line
A: try catch do not work like then catch.
try {
var res = await Vue.axios({
url: baseUrl + request.Url,
params: request.Params,
method: 'GET',
headers
})
}
catch(error) {
console.error('Failed to GET: ' + error)
if (typeof error.response !== 'undefined' && typeof error.response.data !== 'undefined' && error.response.data !== null) {
throw new Error(error.response.data)
} else {
throw error
}
}
This is how try catch blocks are used in js.
await resolves the promise
if errors are caught while resolving promise then the error is thrown to catch block
| |
doc_23526996
|
import smtplib, ssl
email = "myemail@gmail.com"
password = "mypassword"
message = """\
Hello World
"""
receiver = "reciveremail@gmail.com"
port = 465
sslcontext = ssl.create_default_context()
connection = smtplib.SMTP_SSL("smtp.gmail.com", port, context=sslcontext)
connection.login(email, password)
connection.sendmail(email, reciever, message)
print("sent")
A: You can make the subject as a header of the body text.
Try this :
import smtplib, ssl
email = "myemail@gmail.com"
password = "mypassword"
subject= "Put here your subject"
body = """\
Hello World
"""
message = 'Subject: {}\n\n{}'.format(subject, body)
receiver = "reciveremail@gmail.com"
port = 465
sslcontext = ssl.create_default_context()
connection = smtplib.SMTP_SSL("smtp.gmail.com", port, context=sslcontext)
connection.login(email, password)
connection.sendmail(email, reciever, message)
print("sent")
| |
doc_23526997
|
#!/bin/bash
filename='delete'
while read p; do
jq '\'if .tweet | test('\"$p\"'; "i") then . |= . + {vendor: '\"$p\"'} else empty end\' sfilter.json
done < $filename
was following this example
echo $'\'single quote phrase\' "double quote phrase"'
'single quote phrase' "double quote phrase"
A: if escaping a single quote, before the slash \ a single quote should not be required
an example,
echo \$pd
the result should be $pd because you escaped the $ character
| |
doc_23526998
|
import turtle
import random
class turtles:
def __init__(self):
self.turtle.Pen()
self.color(random.randint(0.0, 1.0),random.randint(0.0, 1.0) ,random.randint(0.0, 1.0))
self.begin_fill()
self.circle(50)
self.end_fill()
t1= turtles()
def t1_circle():
t1.left(90)
t1.forward(250)
mycircle(random.randint(0.0, 1.0),random.randint(0.0, 1.0) ,random.randint(0.0, 1.0))
t1_circle()
I expected a ball to be drawn on the screen displaying random colors.
A: You are getting that error because class turtles does not have an attribute 'turtle'. When you specify self.turtle, python expects an attribute named turlte defined in the turtles class.
You can read more into this here
I expected a ball to be drawn on the screen displaying random colors.
Here i will just do the above mentioned. You change the code to meet your exact requirements.
import turtle
import random
class turtles:
def __init__(self):
turtle.Pen()
turtle.color(random.randint(0.0, 1.0),random.randint(0.0, 1.0) ,random.randint(0.0, 1.0))
turtle.begin_fill()
turtle.circle(50)
turtle.end_fill()
while True:
t1= turtles()
A:
I'm trying to make a program that draws five balls on my screen using
the turtle module in python. I'm trying to use as little lines of code
as possible ...
from turtle import *
from random import *
WIDTH, HEIGHT = getscreen().window_width() // 2, getscreen().window_height() // 2
penup()
for _ in range(5):
goto(randrange(50 - WIDTH, WIDTH - 50), randrange(50 - HEIGHT, HEIGHT - 50))
dot(100, (random(), random(), random()))
done()
For a filled circle, the dot() command has some advantages. It's always a filled circle so no begin_fill() and end_fill(). You can pass a color right to the dot() function. It prints a circle of a given diameter (not radius) centered on the turtle (not with turtle on the edge like circle().
| |
doc_23526999
|
public static void ParceIntricaciesJabber(ref CardDetails[] WhichArray)
{
WhichArray[0].ID = 50;
WhichArray[0].Type = "None";
}
In calling:
ParceIntricaciesJabber(ref OpponentCards);
After I call the function though, another Array called PlayerCards is affected in the exact same way as OpponentCards - despite being declared as two different arrays. They have the same number of elements and the same data Type, and that's it.
This probably should be obvious but i'm not seeing it. The code works in VB.NET. What am I doing wrong?
EDIT: Initialization Code:
public static class Module1{
public static CardDetails[] PlayerCards = new CardDetails[100];
public static CardDetails[] OpponentCards = new CardDetails[100];
}
And also when navigating to the Form
for (int n = 1; n <= 100; n++)
{
Module1.PlayerCards[n] = new CardDetails();
Module1.OpponentCards[n] = new CardDetails();
}
A: My guess is that you are sharing the reference to the arrays. Even though it is structs inside the array, the array itself is a reference type. You will need to post your array instantiation code to verify one way or the other though
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.