query_id stringlengths 4 64 | query_authorID stringlengths 6 40 | query_text stringlengths 66 72.1k | candidate_id stringlengths 5 64 | candidate_authorID stringlengths 6 40 | candidate_text stringlengths 9 101k |
|---|---|---|---|---|---|
7309ab0b54203ee1b35142471f525ccaa28ac0017f89b5657b19ba081db8314b | ['9129d876b5984f018da6c1d257700cbf'] | Could you please help me to fix this issue?
I am new to gstreamer and pipeline facing tough time to debug below issue
I am trying to do hls stteam of video capture output using gst-launch-1.0 command
I run below command in ubuntu 18.04
gst-launch-1.0 v4l2src device=/dev/video0 ! videorate ! videoscale ! video/x-raw,framerate=30000/1001,width=720,height=480 ! x264enc bitrate=256
! muxer.sink_65 audiotestsrc ! audio/x-raw,rate=48000,channels=1
! avenc_aac bitrate=32000 ! muxer.sink_66 mpegtsmux name=muxer prog-map=program_map,
sink_65=10,sink_66=10 ! tee name=output_tee ! queue !
hlssink location=/var/www/segment-%05d.ts playlist-location=/var/www/index.m3u8 max-files=20 target-duration=15
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
ERROR: from element /GstPipeline:pipeline0/GstV4l2Src:v4l2src0: Internal data stream error.
Additional debug info:
gstbasesrc.c(3055): gst_base_src_loop (): /GstPipeline:pipeline0/GstV4l2Src:v4l2src0:
streaming stopped, reason not-negotiated (-4)
ERROR: pipeline doesn't want to preroll.
Setting pipeline to PAUSED ...
Setting pipeline to READY ...
Setting pipeline to NULL ...
Freeing pipeline ...
I am using HD60 Game Live video capture card which support [0]: 'MJPG' (Motion-JPEG, compressed) video codec
Linux 8d78e22141e4 4.15.0-91-generic #92~16.04.1-Ubuntu SMP Fri Feb 28 14:57:22 UTC 2020 x86_64 GNU/Linux
root@8d78e22141e4:/code# lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 10 (<PERSON>)
Release: 10
Codename: <PERSON>
| a6fe999d73a0212dafb3aa42ff4f8ce4cfa33a843e232f93a400ac4822db93de | ['9129d876b5984f018da6c1d257700cbf'] | I came across https://www.npmjs.com/package/react-hls-player where it is mentioned how to use hls player in reactjs
This is sample code i have written but i couldn't figureout how to use hlsConfig object. Can someone help me how and where to use hlsConfig object ?
import React from 'react';
import ReactHlsPlayer from 'react-hls-player'
export default class HLSPlayer extends React.Component {
render() {
return (
<ReactHlsPlayer
url='https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8'
autoplay={true}
controls={true}
width="1200"
height="auto"
/>
)
}
}
|
b4179c07b4a9c34ea5553ce1b1d59105894e74f8ac68d83e523febc539cf049f | ['9130eb3295ef4fcba8a0293de9d366f7'] | Does anyone know if there's an option in Sublime Text 2 (or some other editing program) where I can change content in multiple files at one time?
Let's say I want to change my phone number in the footer on every page, I have to open all files, and copy past it on every single page by myself. I know Wordpress or a local server is a solution, but can it be done without that?
Thank you.
| c8625316d9a808b8a46a67689a20ebfd55a08eed2b980ed392cb4390124415e5 | ['9130eb3295ef4fcba8a0293de9d366f7'] | I have a contact form in the popover plugin from Bootstrap 3. It's initiated this way:
$(document).ready(function() {
$(function(){
$('[rel=popover]').popover({
html : true,
placement : 'bottom',
trigger : 'click',
content: function() {
return $('#popover_content_wrapper').html();
}
});
});
});
I'm displaying it this way:
<a class="call" rel="popover">call me back</a>
<div id="popover_content_wrapper" style="display: none"><?php echo do_shortcode( '[contact-form-7 id="84" title="Call me back"]' ); ?></div>
So when you click on the call me back button the contact form shows up. That's fine, it works. But when filling the form and sending it, there's no AJAX so the page refreshes. You have to hit the call me back button again to see the feedback from the form.
Is there a way that the feedback can be loaded in AJAX in the popover?
If I place the contact form code outside the popover tags, the AJAX works. Deleting style="display: none" in the popover_content_wrapper div fixes it too. But then you see the form without first clicking on the call me back button.
Thanks in advance.
|
b5306fd67584bb3eac581bc3d9fcb72540d481496bd1c78381e6cd510a24fb6e | ['9133c785c59d4d2cba779f6a74f8bf22'] | Figured it out:
public bool createReport_NewMinusBase(string currentWorkingDirectory, string Book1, string Book2, double tolerance)
{
tolerance = 0.0001;
myExcel.Application excelApp = new myExcel.Application(); // Creates a new Excel Application
excelApp.Visible = false; // Makes Excel visible to the user.
excelApp.Application.DisplayAlerts = false;
//useful for COM object interaction
object missing = System.Reflection.Missing.Value;
//Return value
bool wereDifferences = false;
//Comparison objects
object objNew = null;
object objBase = null;
//source: http://www.codeproject.com/KB/office/csharp_excel.aspx
//xlApp.Workbooks.Open(reportFolder + reportName, 0, false, 5, "", "", false, myExcel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Open BASE FILE
myExcel.Workbook excelWorkbook1 = excelApp.Workbooks.Open(@currentWorkingDirectory + Book1, 0,
missing, missing, missing, missing, missing, missing,
missing,missing, missing, missing, missing, missing, missing);
//OPEN NEW FILE
myExcel.Workbook excelWorkbook2 = excelApp.Workbooks.Open(@currentWorkingDirectory + Book2, 0,
missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing);
myExcel.Workbook excelWorkbook3 = excelApp.Application.Workbooks.Add(myExcel.XlWBATemplate.xlWBATWorksheet);
myExcel.Worksheet wsBase;
myExcel.Worksheet wsDiff;
myExcel.Worksheet wsNew;
try
{
wsBase = (myExcel.Worksheet)excelApp.Workbooks[Book1].Sheets["Sheet1"];
wsNew = (myExcel.Worksheet)excelApp.Workbooks[Book2].Sheets["Sheet1"];
wsDiff = (myExcel.Worksheet)excelWorkbook3.Worksheets.get_Item(1);
}
catch
{
throw new Exception("Excel file does not contain properly formatted worksheets");
}
//Copy Sheet from Excel Book "NEW" to "NEW(-)BASE"
myExcel.Worksheet source_sheet;
source_sheet = (myExcel.Worksheet)excelApp.Workbooks[Book2].Sheets["Sheet1"];
source_sheet.UsedRange.Copy();
wsDiff.Paste();
//Determine working area
int row = 0;
int col = 0;
int maxR = 0;
int maxC = 0;
int lr1 = 0;
int lr2 = 0;
int lc1 = 0;
int lc2 = 0;
{
lr1 = wsNew.UsedRange.Rows.Count;
lc1 = wsNew.UsedRange.Columns.Count;
}
{
lr2 = wsBase.UsedRange.Rows.Count;
lc2 = wsBase.UsedRange.Columns.Count;
}
maxR = lr1;
maxC = lc1;
if (maxR < lr2) maxR = lr2;
if (maxC < lc2) maxC = lc2;
//===================================================
//Compare Cells
//===================================================
for (row = 1; row <= maxR; row++)
{
for (col = 1; col <= maxC; col++)
{
//Get cell values
objNew = ((myExcel.Range)wsNew.Cells[row, col]).Value2;
objBase = ((myExcel.Range)wsBase.Cells[row, col]).Value2;
//If they are not equivilante
if (!equiv(objNew, objBase, tolerance))
{
wereDifferences = true;
//Mark differing cells
((myExcel.Range)wsNew.Cells[row, col]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
((myExcel.Range)wsBase.Cells[row, col]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
if ((objNew == null))
{
((myExcel.Range)wsDiff.Cells[row, col]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
}
else if (objNew.GetType().ToString() == "System.String")
{
((myExcel.Range)wsDiff.Cells[row, col]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
}
else
{
((myExcel.Range)wsDiff.Cells[row, col]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
((myExcel.Range)wsDiff.Cells[row, col]).Value2 = ((myExcel.Range)wsNew.Cells[row, col]).Value2 - ((myExcel.Range)wsBase.Cells[row, col]).Value2;
}
}
else //They are equivalent
{
if ((objNew == null))
{
}
else if (objNew.GetType().ToString() == "System.String")
{
}
else
{
((myExcel.Range)wsDiff.Cells[row, col]).Value2 = ((myExcel.Range)wsNew.Cells[row, col]).Value2 - ((myExcel.Range)wsBase.Cells[row, col]).Value2;
}
}
}
}
// Copy formatting
myExcel.Range range1 = wsBase.get_Range((myExcel.Range)wsBase.Cells[1, 1], (myExcel.Range)wsBase.Cells[maxR, maxC]);
myExcel.Range range2 = wsDiff.get_Range((myExcel.Range)wsDiff.Cells[1, 1], (myExcel.Range)wsDiff.Cells[maxR, maxC]);
range1.Copy();
range2.PasteSpecial(myExcel.XlPasteType.xlPasteColumnWidths);
excelApp.Workbooks[Book1].Close(false, false, false);
excelApp.Workbooks[Book2].Close(false, false, false);
string Book3 = "reporttestpc.xlsx"; //"reportBaseMinusNew.xlsx"
if (File.Exists(currentWorkingDirectory + Book3))
{
File.Delete(currentWorkingDirectory + Book3);
}
excelWorkbook3.SaveAs(currentWorkingDirectory + Book3, Type.Missing, Type.Missing,
Type.Missing, false, false, myExcel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//excelApp.Workbooks[Book3].Close(false, false, false);
excelApp.Visible = true;
return wereDifferences;
}
/// Determines whether two objects are equivalent
/// Numbers are equivalent within the specified tolerance
/// Strings are equivalent if they are identical
/// obj1 and obj2 are the two objects being compared
/// tolerance is the maximum difference between two numbers for them to be deemed equivalent
private bool equiv(object obj1, object obj2, double tolerance)
{
if ((obj1 == null) && (obj2 == null))
{
return true;
}
else if ((obj1 == null) || (obj2 == null))
{
return false;
}
//if both are numeric
if (IsNumeric(obj1))
{
if (IsNumeric(obj2))
{
if (Math.Abs(Convert.ToDouble(obj2) - Convert.ToDouble(obj1)) < tolerance)
{
return true; //If they are within tolerance
}
else
{
return false; //If they are outside tolerance
}
}
else
{
return false; //If only one is numeric
}
}
//Now assuming both are just random strings
else
{
if ((string)obj1 == (string)obj2)
{
return true;
}
else
{
return false;
}
}
}
// Test whether a given object represents a number
internal static bool IsNumeric(object ObjectToTest)
{
if (ObjectToTest == null)
{
return false;
}
else
{
double OutValue;
return double.TryParse(ObjectToTest.ToString().Trim(),
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.CurrentCulture,
out OutValue);
}
}
///
| 572c8f2e5afe208b7b47a40cee26435972cd96e5b68eb7c6e4cbf007ceff6f33 | ['9133c785c59d4d2cba779f6a74f8bf22'] | I am trying to get an item[i] to a string from a ListView. I just don't seem to understand what I am supposed to do, when the ListView is on another thread.
public delegate void getCurrentItemCallBack (int location);
...
private void runAsThread()
{
While (..>i)
{
//I tried the following //Doesn't work.
//string item_path = listView.Item[i].toString();
//attempting thread safe. How do I get it to return a string?
string item_path = GetCurrentItem(i);
}
}
private void GetCurrentItem(int location)
{
if (this.listViewModels.InvokeRequired)
{
getCurrentItemCallback d = new getCurrentItemCallback(GetCurrentItem);
this.Invoke(d, new object[] { location });
}
else
{
this.listViewModels.Items[location].ToString();
}
}
What am I missing?
|
40280d939a981360456c8071bbb39c8ec29089688de10a31a9cd9e228f166337 | ['9137c20af7194b8082e025c67f679715'] | простой пример и я думаю вы поймете как применить к вашему коду:
var t_event={};
t_event[0]=function(){return;};
t_event[1]=function(a,b){ return console.log(a*b);},
test;
function test(_t,_event,_a,_b){
return _event[(!(_t === 1))+0](_a,_b);
};
test(0,t_event,3,5);
можно делать переход по "индексу" [0/1] в разных вариантах, это и будет отработка условия, просто проверки как таковой нет, по результату предыдущего действия (false/true) вы сразу "проваливаетесь" через индекс в нужную функцию или событие...
| accd31e9d056c1feab22222c22281a587aa575c7c67e2976ef2eea529b715d8a | ['9137c20af7194b8082e025c67f679715'] | все таки ответ напишу, хоть уже и время прошло.. Сразу скажу мне помогали.
import static java.lang.System.out;
interface Func {
void apply(int a, String b);
}
class B {
void b0(int a, String b) {
out.println("b0");
}
void b1(int a, String b) {
out.println("b1");
}
}
class D0 implements Func {
public void apply(int a, String b) {
out.println("d0");
}
}
public class Sample {
public static void main(String[] args) {
new Sample().execute(5, "Hello, world!");
}
Func[] functions;
void a0(int a, String b) {
out.println("a0: a=" + a + ", b=" + b);
}
static void a1(int a, String b) {
out.println("a1");
}
Sample() {
// разные способы объявления функций
B beta = new B(); // обычный класс
Func c0 = (a, b) -> out.println("c0"); // lambda
Func c1 = new Func() { // анонимный класс
public void apply(int a, String b) {
out.println("a1");
}
};
Func d0 = new D0(); // обычный класс
functions = new Func[]{
this<IP_ADDRESS>, // сылка на метод
Sample<IP_ADDRESS>, // сылка на метод
beta<IP_ADDRESS>, // сылка на метод
beta<IP_ADDRESS>, // сылка на метод
c0,
c1,
d0,
(a, b) -> out.println("d1"), // lambda
};
}
void execute(int a, String b) {
for (Func f: functions) {
f.apply(a, b);
}
}
}
... это максимально близко к тому что я предлагал. Извините если что не так.
|
015d56ca9b75987311e7f0d87d856fa46ef5a68e2176cbc1bc2bc1d9a33ae03b | ['9142c8289153466fbf25bc33ef63a3c5'] | I can double confirm your answer. I was fiddling with my enderman farm just now and accidentally added a block under one of the tripwire hooks. After a random amount of time, the tripwire inactivates(or I should say, the tripwire hooks "retracts") with a "spring" sound. The tripwire activates again immediately when I removed the block under the tripwire hook. Weird. | 4d3eed7bb9ee59a7c08ed28956601017893a5b73076824e1108df985fa27af98 | ['9142c8289153466fbf25bc33ef63a3c5'] | As you are using TexnicCenter, the solution is to add two (or even three, if you use booktables for example) additional compilations.
Just define a new profile (as copy of your currently used profile) and edit it. In the post-execution tab you add two (or whatever number of additional compilations you need) tasks, and in each of your task you copy the command and command line arguments from the first (La)TeX tab. When new pressing F7, the original compilation run including bibtex (or biber, if you switched it) and the post compilation runs are executed one after another.
But be aware, compilation may take forever. I would only suggest this for editing a final version.
|
bb4f99d90af5ffce6c3c6faeafa8ab9d32a99431fbd3cf6e28549ea69409a912 | ['914921ee72de474ca8b2d27cea1fb86d'] | Use this code it automatically retrieves the data from Disqus and displays
<div id="recentcomments" class="dsq-widget"><script type="text/javascript" src="http://YOURBLOG.disqus.com/recent_comments_widget.js?num_items=5&hide_avatars=1&avatar_size=50&excerpt_length=10"></script></div>
Do not forget to mention your blog name in place of YOURBLOG.
| de580c2b30a57c3ab27547373f4e5ed24bae55dfccaa96b30fee7a5b2457d350 | ['914921ee72de474ca8b2d27cea1fb86d'] | This is not POST request. It is GET. The API endpoint is like this
http://sqs.us-east-1.amazonaws.com/123456789012/testQueue/
?Action=ReceiveMessage
&WaitTimeSeconds=10
&MaxNumberOfMessages=5
&VisibilityTimeout=15
&AttributeName=All;
&Version=2012-11-05
&Expires=2013-10-25T22%3A52%3A43PST
&AUTHPARAMS
I was not mentioning the request parameters so not getting the result. That was the issue.
|
dc5903b56dbebfa0bddc4f928cc17c28fc466b970be38ab9ecd915716d975912 | ['914986eddd7f4fbfa045cd71fc515cf2'] | import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
private static ArrayList<Countries> arr =null;
static String country;
static String capital;
static String cities;
static String answer;
public static void main(String args[]) throws IOException{
Scanner keybord = new Scanner(System.in);
ArrayList<Countries> d = read("data.txt");
String res = "";
for(int i = 0; i < d.size(); i++){
res += d.get(i).toString();
answer = keybord.nextLine();
if(answer.equalsIgnoreCase(d.get(i).getCapital()))
res+= "The answer is true!";
else
res += "The answer is not true" + "The answer is " + d.get(i).getCapital();
System.out.println(res);
}
}
public static ArrayList<Countries> read(String filename) throws IOException{
Scanner scan = new Scanner(new File(filename));
while(scan.hasNext()){
country = scan.nextLine(); //System.out.println(country);
String cities1 = scan.nextLine(); //System.out.println(cities1);
String cities2 = scan.nextLine(); //System.out.println(cities2);
String cities3 = scan.nextLine(); //System.out.println(cities3);
String cities4 = scan.nextLine(); //System.out.println(cities4);
String capital = scan.nextLine(); //System.out.println(capital);
Countries c = new Countries(cities1, cities2, cities3, cities4, capital);
arr.add(c); // where i get the exception
scan.nextLine();
}
return arr;
}
I could not understand why I'm getting the null pointer exception while I'm trying to add the countries to the array list? should not I instantiate it as a null before creating it?
| ab8541f5001053d21c307efdb365d83441e3faf4e427f14d5b56da778208b598 | ['914986eddd7f4fbfa045cd71fc515cf2'] | Is there any way that I can find all subdirectories for one link? Should I get the permission? For example, in the lecture instructor opened the solutions by entering some keywords after www.site.com/keyword. Now I cannot remember the word, whatever I try, I cannot find, but I know there is a file. That's why I want to see the files, other pages for the link.
|
ca8001da8307a7c5490e94829b34a48177aa1dff7ec69aae6419b34c2a0ac358 | ['914ff6dfcc7a4d658e3f3058b6d4c0ab'] | <PERSON> My point was that since there was $700 million in the fund, it had a certain sureness to it, though I do realize now, how silly that statement was. Also, on this topic why do you think people **do** choose to buy this kind of mutual fund as opposed to a Vanguard of Fidelity mutual fund? | 9f72775d0bdc1ed9e88a8d5ead56a52fc09192aafd42fdeeaf4e3f048d59b2c2 | ['914ff6dfcc7a4d658e3f3058b6d4c0ab'] | I have Sony Xperia M2, and as you probably know, this phone will not get the new Android L update from Sony.
So is there any way to install the Android L manually?
I don't care to root my device and install a custom ROM which compatible with the new version... but is it actually possible to update my device version?
|
8fb88813e21c46d3152d189c26d3642680b376569b40a87858c9a380f61ed011 | ['9157df57ba3646a39a199a0692837ecb'] | I was afraid this might be the case, after not being able to find any examples after hours of Googling. :-/ I had hoped that WordPress had some method it used when displaying available updates on the plugin list, but if I understand you correctly, it's relying on each plugin to provide this? I don't suppose there's anything in WordPress to hook into at a layer above the individual coding that each plugin chooses to use? | b21f913cf12907760452361dbecfc6fa9d6258a56c3091000417793ffb410b90 | ['9157df57ba3646a39a199a0692837ecb'] | Is the sentence in the title correct?
I had to join the sentences below into one using adjective clauses.
This is a street. Many famous churches are on it.
Traditional English: This is a street on which many famous churches are.
Modern English: This is a street which many famous churches are on.
Are they both correct?
|
3c9c1e5d07f59c1dbd21bdf740fa72a1298a41ccdbede0278749218009907606 | ['91589fec79254adcb4a8eaaeac74656b'] | The workaround is to use the encoding="bytes" like this:
pickled_bytes = bytes(pickled_str, encoding='latin1') # If your input is a string(not my case)
data = pickle.loads(pickled_bytes, encoding='bytes')
(Thanks to <PERSON> for the suggestion)
Issue still opened at http://bugs.python.org/issue22005 as to why this is required.
| c6e326f204a2371a202b37423c49f415964aa9a5e3140da4d844ecc7c12cc9cf | ['91589fec79254adcb4a8eaaeac74656b'] | I chose to use pickle (+base64+TCP sockets) to communicate data between my python3 code and legacy python2 code, but I am having trouble with datetime objects:
The PY3 object unpickles well on PY2, but the reverse raises a TypeError when calling the datetime constructor, then a UnicodeEncodeError in the load_reduce function.
A short test program & the log, including dis output of both PY2 and PY3 pickles, are available in this gist
I am using pickle.dumps(reply, protocol=2) in PY2 then pickle._loads(pickled, fix_imports=True, encoding='latin1') in PY3 (tried None and utf-8 without success)
Native cPickle loads decoding fails too, I am only using pure python's _loads for debugging.
Is this a datetime bug ? Maybe datetime.__getstate__/__setstate__ implementations are not compatible ?
Any remark on the code is welcome...
Complement
PY-3.4.0 pickle:
0: \x80 PROTO 2
2: c GLOBAL 'datetime datetime'
21: q BINPUT 0
23: c GLOBAL '_codecs encode'
39: q BINPUT 1
41: X BINUNICODE u'\x07\xde\x07\x11\x0f\x06\x11\x05\n\x90'
58: q BINPUT 2
60: X BINUNICODE u'latin1'
71: q BINPUT 3
73: \x86 TUPLE2
74: q BINPUT 4
76: R REDUCE
77: q BINPUT 5
79: \x85 TUPLE1
80: q BINPUT 6
82: R REDUCE
83: q BINPUT 7
85: . STOP
PY-2.7.6 pickle:
0: \\x80 PROTO 2
2: c GLOBAL 'datetime datetime'
21: q BINPUT 0
23: U SHORT_BINSTRING '\\x07\xc3\x9e\\x07\\x11\\x0f\\x06\\x11\\x05\\n\\x90'
35: q BINPUT 1
37: \\x85 TUPLE1
38: q BINPUT 2
40: R REDUCE
41: q BINPUT 3
43: ] EMPTY_LIST
44: q BINPUT 4
46: N NONE
47: \\x87 TUPLE3
48: q BINPUT 5
50: . STOP
PY-3.4.0 pickle.load_reduce:
def load_reduce(self):
stack = self.stack
args = stack.pop()
func = stack[-1]
try:
value = func(*args)
except:
print(sys.exc_info())
print(func, args)
raise
stack[-1] = value
dispatch[REDUCE[0]] = load_reduce
PY-3.4.0 datetime pickle support:
# Pickle support.
def _getstate(self):
<PERSON>, <PERSON> = divmod(self._year, 256)
us2, <PERSON> = divmod(self._microsecond, 256)
us1, us2 = divmod(us2, 256)
basestate = bytes([yhi, <PERSON>, self._month, self._day,
self._hour, self._minute, self._second,
us1, us2, us3])
if self._tzinfo is None:
return (basestate,)
else:
return (basestate, self._tzinfo)
def __setstate(self, string, tzinfo):
(<PERSON>, <PERSON>, self._month, self._day, self._hour,
self._minute, self._second, us1, us2, us3) = string
self._year = yhi * 256 + ylo
self._microsecond = (((us1 << 8) | us2) << 8) | us3
if tzinfo is None or isinstance(tzinfo, _tzinfo_class):
self._tzinfo = tzinfo
else:
raise TypeError("bad tzinfo state arg %r" % tzinfo)
def __reduce__(self):
return (self.__class__, self._getstate())
|
03e2b6c8041883c9aa9a5525bef09231f3206a63d706a34590c1d5aea99b49a9 | ['915bb93609b7401491c6da6465167817'] | I have a collection on my class that uses @XmlElementWrapper to wrap the collection in a extra element.
So, my class looks something like this:
class A {
@XmlElement(name = "bee")
@XmlElementWrapper
public List<B> bees;
}
And my XML then looks something like:
<a>
<bees>
<bee>...</bee>
<bee>...</bee>
</bees>
</a>
Great, this is what I wanted. However, when I try and marshall into JSON, I get this:
{
"bees": {
"bee": [
....
]
}
}
And I don't want that extra "bee" key there.
Is it possible to somehow have MOXy ignore the XmlElement part when doing this marshalling? because I still need the name to be "bees" and not "bee", and I don't want both.
I'm using MOXy 2.4.1 and javax.persistence 2.0.0.
| 57d47ea7db7f3c2bd49169d4307b41cb1d37a59e23dff25f2a1c706d7e20a3f8 | ['915bb93609b7401491c6da6465167817'] | I have a pretty normal spring security setup (using spring boot) where all the form login is using a ajax based approach (no redirect, etc), and this is working fine for form login.
For basic authentication I want to now also properly handle failed login attempts, and there seems to be some issues here: I can't rely on ControllerAdvice to catch the exceptions anymore which is fine, I tried a custom BasicAuthenticationEntryPoint to do some changes... but all I could do from there was to change the actual exception being thrown.. it was still not being caught by my controller advice.
So what I'm wondering, I understand that spring security works outside of the spring mvc/advice world, so how can I catch and change the default message that is being sent to the user? (for basic auth, for form/session, this is already working fine..)
|
f48e209720a7152567d975e3fb1283a43e5cf0876816609c6318285376f2c39c | ['916a50ca4973424ea20aa4f4d3d4729d'] | I have a spring boot application which contains web application build with Polymer. Polymer web application builds two version one with ES5 And one ES6. It mean i have two separate web application builds. Now on based of user agent like for Chrome & firefox i want to serve ES6 version and for IE11 I have to serve Es5 version.
Both versions of apps are placed inside static folder of spring boot like
/static/es5
/static/es6
Both of version contains index.html file and contains same folder structure inside only difference is of code.
I want user to hit same URL and they should get served resources dynamically based on their user-agent/browser.
i have defined following properties in application.properties.
spring.resources.static-locations=classpath:/public/es5/
How can i make es5 & es6 resources serve dynamically ???
`
| f91ef8ad148e57697eabccffa157976a69d42bcb91c54f8a39b3b04a484a8029 | ['916a50ca4973424ea20aa4f4d3d4729d'] | I'm unable to get data back from ajax request from java servlet using Json object..here is the code below we are using channel api in google app engine .we need to implement chat application.
displayFriendList = function() {
var txt = document.createElement("div");
txt.innerHTML = "<p> Logged in as <b>" + userid
+ "</b><p><hr />";
document.getElementById("friendlistdiv").appendChild(
txt);
var dataString ='userId='+userid;
$.ajax({
type : "POST",
url : "/OnlineUserServlet",
data : dataString,
success : function(html) {
alert(html.frndsList[0].friend);
}
});
};
Java Servlet Code:
while(friendList.hasNext()){
friend = friendList.next() ;
if(!friend.equals(user)){
Map<String, String> state = new HashMap<String, String>();
state.put("friend", friend);
state.put("type","updateFriendList");
state.put("message",user);
state1.add(state);
message = new JSONObject(state);
channelService.sendMessage(
new ChannelMessage(friend,message.toString()));
}
i++;
}
Map<String, String> <PERSON> = new HashMap<String, String>();
statejason.put("friendsList", state1.toString());
//System.out.print("hello"+message.toString());
response.setContentType("text/plain");
response.getWriter().print(statejason.toString());
}
|
c56d0eaa60c50356229a5f21e7a69432f7ed5ddf30059c07331f2054fac63c33 | ['916fea73170648809fa508b25303cbc8'] | I would like to ask question about the output from sar -q . I appreciate if someone can help me out with understanding runq-sz.
I have a system which cpu threads are 8 cpu threads on RHEL 7.2 .
[ywatanabe@host2 ~]$ cat /proc/cpuinfo | grep processor | wc -l
8
Below is sar -q result from my system but runq-sz seems to be low compared to ldavg-1 .
runq-sz plist-sz ldavg-1 ldavg-5 ldavg-15 blocked
05:10:01 PM 0 361 0.29 1.68 2.14 0
05:11:01 PM 0 363 1.18 1.61 2.08 2
05:12:01 PM 0 363 7.03 3.15 2.58 1
05:13:01 PM 0 365 8.12 4.15 2.96 1
05:14:01 PM 3 371 7.40 4.64 3.20 1
05:15:01 PM 2 370 7.57 5.26 3.51 1
05:16:01 PM 0 366 8.42 5.90 3.84 1
05:17:01 PM 0 365 8.78 6.45 4.16 1
05:18:01 PM 0 363 7.05 6.40 4.28 2
05:19:02 PM 1 364 8.05 6.74 4.53 0
05:20:01 PM 0 367 7.96 6.96 4.74 1
05:21:01 PM 0 367 7.86 7.11 4.93 1
05:22:01 PM 1 366 7.84 7.31 5.14 0
From the man sar , I was thinking that runq-sz represents the number of tasks inside the run queue which states are TASK_RUNNING which corresponds to R sate in ps .
runq-sz
Run queue length (number of tasks waiting for run time).
What does runq-sz actually represent ?
| 43fcaa2865d537d517fefc6c5a2104257c455357d65dfc55a6228dac05b1dced | ['916fea73170648809fa508b25303cbc8'] | There is a more forceful way to get rid of dead links to mapped network drives.
You could delete the reference in your registry.
Just open "regedit.exe" and expand the key "HKEY_CURRENT_USER" and the key "Network". There you will see keys with letters that will represent the Mapped Drive Letters. When you delete a letter on "regedit.exe", the mapped drive letter will vanish on the next Windows restart cycle.
|
d7caa55f703de7b7970fcecc69ac104aca9de13e5fb20dddf68dc385f84543eb | ['9180b8827d1c4b33b84393fefb9b14c5'] | The `ntpq -p` gets me this:
` remote refid st t when poll reach delay offset jitter
==============================================================================
*ntp.your.org .CDMA. 1 u 795 1024 377 39.404 1.084 19.478
+clocka.ntpjs.or <IP_ADDRESS> 2 u 376 1024 377 39.151 7.953 4.993
+li290-38.member <IP_ADDRESS> 2 u 664 1024 177 61.149 4.258 14.380
+<IP_ADDRESS> <IP_ADDRESS><PHONE_NUMBER> 2 u 376 1024 377 39.151 7.953 4.993
+li290-38.member 128.138.141.172 2 u 664 1024 177 61.149 4.258 14.380
+209.208.79.69 130.207.244.240 2 u 407 1024 377 47.402 0.707 24.355` | 91117b473b87937efbf0916493c3311d62dd4d2c82660ed9f2c3c1ef40a80c1a | ['9180b8827d1c4b33b84393fefb9b14c5'] | I have a Python script that runs at startup and needs the correct time in order to function properly. I have setup the raspi-config to wait for a network connection before continuing so the code won't run until there is an internet connection (I think!). However, I have noticed that after a reboot it may take several seconds after the Python code gets started before the system gets around to running the NTP process that updates the system clock.
Is there some way to test to see when the internal clock gets updated by the NTP process? Is there some resource that keeps track of the last NTP time sync event? And how often does the RPi resync its clock using the NTP (daily, hourly weekly)?
|
297bbe8d8beed5e2484c236cb4a8088f20d4c605f3b78e1b04348cc2bc892df4 | ['91816340c89c44c6afa5f495c33ce1e1'] | newArray should include reversed version of theall items in myArray. After that, newArray should be reversed and joined with space in order to get the reversed version of the input string.
Here is the code:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.map(function (item) {
return item.split("").reverse().join("");
});
console.log(newArray);
return newArray.reverse().join(" ") === string;
}
console.log(palindromeChecker("dad did what"));
| 1e73b7f68d4644f20f671f08d500dfefe2140a249fce0bdea1eaf787ca3cc3a4 | ['91816340c89c44c6afa5f495c33ce1e1'] | Better to write your custom fromNow function.
function myFromNow(time) {
let now = moment();
return now.isSame(time, 'day') ? time.fromNow() : time.format();
}
let time1 = moment('2017-04-12T17:37:06.886Z');
let time2 = moment('2018-10-12T17:37:06.886Z');
console.log(myFromNow(time1)); //2017-04-12T19:37:06+02:00
console.log(myFromNow(time2)); //in 5 hours
|
172035a7e08aa73e198b9bdb6d694137454f5de26b742e95e1358abc48e32597 | ['9183f13718ad437b8ee700286ddaac0e'] | podrias usar una condición de manera rapida segun ejemplo con expresión regular.
string nombre = Console.ReadLine();
Regex regex = new Regex(@"/^[ñA-Za-z]*[ñA-Za-z][ñA-Za-z]*$/");
if (regex.IsMatch(compare))
{
//true
Console.WriteLine($"Tu nombre es {nombre}");
}
else {
//false
Console.WriteLine($"Tu nombre no es valido.");
}
espero te ayude.
Saludos.
| 84bdcac9a8496d282259800e2472918ff5913b7611606283dba498c54e33dd40 | ['9183f13718ad437b8ee700286ddaac0e'] | Ubuntu home server on laptop/wireless, when accessing the the database from another wireless laptop or desktop such as www.example.com/phpmyadmin, it causes wireless internet to be delay and broken frequently. I have had updated and upgraded this OS to the latest version and it's still doesn't help.
On a desktop it seems to be fine.
I'm thinking of switching from wireless to wire, how do you do it on the Ubuntu?
|
a91d407df9b413df460bffff4e18aa7fcb88e91d06b15d5581691af28e726fc8 | ['918fa4e5ba3f44a58d16a4a6f5c7ab3f'] | I am new to ASP and have just started to learn it. I am looking for some websites, where I can execute my ASP code online. I looked at ideone, codepad, compile online, etc. But, they do not support ASP. Can anyone tell me about an online compiler for executing ASP code?
Thanks in advance...
| f6e28cf2c2c303ce680e08cc907e51d05664b61a7b7bd3260c362b38e7a5e6a4 | ['918fa4e5ba3f44a58d16a4a6f5c7ab3f'] | I am working on a project, were I need to store a 25 digit number. When I tried to use BIGINT data format, it shows out of range. Then I stored it using VARCHAR data type. But I also need to export this into an MS-EXCEL sheet.
When I export it, Excel show only 13-14 higher digits, the remaining lower ones are getting rounded off to which makes them 0's.
My Source code is mentioned below:
<?php
$conn = mysqli_connect("localhost", "root", "", "dis");
$output='';
$sql= "SELECT `polid`, `inscompanyid`, polno FROM `policies` order by polid desc";
$res = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if(!$res || mysqli_num_rows($res)){
$output .='
<table class="table" border="1">
<tr>
<th>asdf</th>
<th>qwer</th>
<th>zcxv</th>
</tr>
';
while($row=mysqli_fetch_assoc($res))
{
$output.='
<tr>
<td>'.$row["polid"].'</td>
<td>'.$row["inscompanyid"].'</td>
<td>'.$row["polno"].'</td>
</tr>
';
}
$output.='</table';
//header("Content-Type: application/xls");
//header("Content-Disposition: attachment; filename=download.xls");
echo $output;
}
?>
|
32132717266fd07c16bc310befeddd92bf4d5d1fec8fcf30b12b9055864a3565 | ['91aec1449a5a40d2b4f200914bc1f0f9'] | rust borrow check looks very smart , it can check and flat reads and writes of loop. but how can I bypass it?
Following code works well:
fn main() {
let mut lines = [
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9],
];
for i in 0 .. lines.len() {
let line = &lines[i];
for item in line {
// if found odd number, push zero!
if item % 2 == 1 {
lines[i].push(0);
break; // works fine! if comment it, will error!
}
}
}
dbg!(lines);
}
When comment the "break" line, will got:
error[E0502]: cannot borrow `lines[_]` as mutable because it is also borrowed as immutable
--> src/main.rs:13:17
|
10 | let line = &lines[i];
| --------- immutable borrow occurs here
11 | for &item in line {
| ---- immutable borrow later used here
12 | if item == 5 {
13 | lines[1].push(55);
| ^^^^^^^^^^^^^^^^^ mutable borrow occurs here
error: aborting due to previous error
| ede05c88807fb0183e68745fb37c9207cab084d6575d1cf8d66058e9f802c137 | ['91aec1449a5a40d2b4f200914bc1f0f9'] | I want move the elements of HashMap<u64, Vec> key=1 to key=2
use std<IP_ADDRESS>collections<IP_ADDRESS>HashMap;
fn main() {
let mut arr: HashMap<u64, Vec<u64>> = HashMap<IP_ADDRESS>new();
arr.insert(1, vec![10, 11, 12]); // in fact, elments more than 1,000,000, so can't use clone()
arr.insert(2, vec![20, 21, 22]);
// in fact, following operator is in recusive closure, I simplify the expression:
let mut vec1 = arr.get_mut(&1).unwrap();
let mut vec2 = arr.get_mut(&2).unwrap();
// move the elements of key=1 to key=2
for v in vec1 {
vec2.push(vec1.pop().unwrap());
}
}
got error:
error[E0499]: cannot borrow `arr` as mutable more than once at a time
--> src/main.rs:10:20
|
9 | let mut vec1 = arr.get_mut(&1).unwrap();
| --- first mutable borrow occurs here
10 | let mut vec2 = arr.get_mut(&2).unwrap();
| ^^^ second mutable borrow occurs here
11 | for v in vec1 {
| ---- first borrow later used here
Rust check borrow with the whole HashMap, not check the key.
Is there any good way ?
|
903feb6fe4e8209793ff497e614cd4c36cf6ce5584e5263d1086330668429bd0 | ['91b35a44eb9d4ff9828930821d1ac6f8'] | First of all, many thanks for your reply. It has brought many interesting information to my attention resulting in an increased quality of the project.
To start with, I must say there were few mistakes in a code resulting in an improper functionality. All the calls without a stated output_currency should have given a different output, the problem was in a wrong indentation of the last line of a code snippet below (it was on the same level as the second-to-last line and therefore always being rewritten instead of added):
service.py, create_json:
..
output_currencies = output_currency.split(",")
for curr in output_currencies:
if curr != input_currency:
if "output" not in dict:
dict["output"] = {}
dict["output"].update({curr: convert(input_currency, curr, amount)})
..
To continue, here is an updated version of README.md:
Currency Converter
A practical task for a position of Junior Python Developer. Task entry:
https://gist.github.com/MichalCab/c1dce3149d5131d89c5bbddbc602777c
Prerequisites
python 3.4
Requirements
Required libraries can be found in requirements.txt and installed via pip3 install -r requirements.txt
Run application
Run a __main__.py file, either in pyapi or pycli folder depending on a desired form of usage.
Parameters
amount - amount which we want to convert - float
input_currency - input currency - 3 letters name or currency symbol
output_currency - requested/output currency - 3 letters name or currency symbol
Note that a single currency symbol can represent several currencies:
- in case this happens with output_currency, convert to all known currencies with such symbol
- in case this happens with input_currency, conversion is not performer. Rather, an info message with currencies having such symbol
is shown, so a user can specify input_currency more precisely
Output Possibilities:
json with a following structure:
Single input and output currency: {
"input": {
"amount": <float>,
"currency": <3 letter currency code>
}
"output": {
<3 letter currency code>: <float>
} }
Single input and multiple output currencies (in case a currency sign
represents more currencies): {
"input": {
"amount": <float>,
"currency": <3 letter currency code>
}
"output": {
<corresponding 3 letter currency code>: <float>
<corresponding 3 letter currency code>: <float>
.
.
} }
Single input and no output currency - convert to all known currencies:
{
"input": {
"amount": <float>,
"currency": <3 letter currency code>
}
"output": {
<3 letter currency code>: <float>
<3 letter currency code>: <float>
<3 letter currency code>: <float>
.
.
} }
Info message:
Multiple input currencies (in case a currency sign represents more
currencies):
"Input currency not clearly defined. Possible currencies with such symbol: <possible currencies>"
Unknown input currency: "Input currency not recognized"
Unknown output currency: "Output currency not recognized"
Examples
CLI
./currency_converter.py --amount 100.0 --input_currency EUR --output_currency CZK
{
"input": {
"amount": 100.0,
"currency": "EUR"
},
"output": {
"CZK": 2561.78
}
}
./currency_converter.py --amount 0.9 --input_currency € --output_currency AUD
{
"input": {
"amount": 0.9,
"currency": "EUR"
},
"output": {
"AUD": 1.46
}
}
./currency_converter.py --amount 10.92 --input_currency zł
{
"input": {
"amount": 10.92,
"currency": "PLN"
},
"output": {
"HRK": 18.84,
"UZS": 24006.34,
"RUB": 196.93,
"BOB": 20.64,
.
.
.
}
}
./currency_converter.py --amount 10.92 --input_currency EUR --output_currency £
{
"input": {
"amount": 10.92,
"currency": "EUR"
},
"output": {
"GBP": 9.79,
"FKP": 9.77,
"LBP": 19462.11,
"SHP": <PHONE_NUMBER>,
"SYP": 6617.36,
"EGP": 230.18,
"GIP": 9.77
}
}
./currency_converter.py --amount 10.92 --input_currency Nonsense_curr
Input currency not recognized
API
Note: When using curl, currencies symbols are not decoded properly and
therefore not recognised. A recommended tool is Postman.
GET
/currency_converter?amount=4.5&input_currency=₱&output_currency=VEF
HTTP/1.1
{
"input": {
"amount": 4.5,
"currency": "PHP"
},
"output": {
"VEF": 20633.77
}
}
GET /currency_converter?amount=10.92&input_currency=£ HTTP/1.1
Input currency not clearly defined. Possible currencies with such
symbol: SHP,FKP,EGP,LBP,SYP,GIP,GBP
GET /currency_converter?amount=10.92&input_currency=₦ HTTP/1.1
{
"input": {
"amount": 10.92,
"currency": "NGN"
},
"output": {
"HRK": 0.19,
"UZS": 241.47,
"RUB": 1.98,
"BOB": 0.21,
"TZS": 68.63,
"GBP": 0.02,
"GIP": 0.02,
"GTQ": 0.23,
.
.
.
}
}
Now, you mentioned "this isn't production quality code: There are no error checks or fallbacks. If an expected argument is missing e.g. the HTTP API crashes". These are the measures I came up with:
pyapi/__main__.py:
(simple check if arguments are present)
def get():
if 'amount' in request.args and 'input_currency' in request.args:
if 'output_currency' in request.args:
return service.create_json(service.sign_to_abbreviation(request.args['input_currency']),
service.sign_to_abbreviation(request.args['output_currency']),
request.args['amount'])
else:
return service.create_json(service.sign_to_abbreviation(request.args['input_currency']),
"None",
request.args['amount'])
return "Missing arguments"
service.py, contact_api:
(exception if external site is unreachable (+logging of a time needed for a request))
# external converter service
def contact_api(inp, out):
logging.info(" FUNC: contact_api parameters: inp:%s out:%s", inp, out)
api_url_base = 'http://free.currencyconverterapi.com/api/v5/convert'
conversion = inp + "_" + out
payload = {"q": conversion, "compact": "ultra"}
try:
start_time = time.time()
response = requests.get(api_url_base, params=payload, timeout=1) # we have 1 sec to get a response
logging.info(" FUNC: contact_api request elapsed time: %s", time.time() - start_time)
except requests.exceptions.ConnectionError as e:
logging.error(" FUNC: contact_api CONNECTION ERROR: ", e)
return None
logging.info(" FUNC: contact_api Loading from CACHE: %s", response.from_cache)
if response.status_code == 200:
return json.loads(response.content.decode('utf-8'))
return None
I consider this to be simple and functional, could it be done better?
And to finish with, tests could get improved too but that is for another day.
And for a reply to be complete, here is a link to the project: https://github.com/ciso112/kiwi-currencies
| 2aa941d8ad22059b3e844b0e2dbfcacc9fdf97d853d1582ff6f0fb270ad5f5af | ['91b35a44eb9d4ff9828930821d1ac6f8'] | On a purely theoretical level <PERSON> is actually extracting a natural number from an infinite sample if you consider the rules he is following.
for example if he throws 6 8 3 4 9 10(end) then he extracted the number: 94386
However he is doing that with restrictions.
The first restriction is that he can never extract a number that has "0" in it. The second, and more important restriction, is that the higher is the magnitude of a number the lower is the probability for it to be extracted. Any number in a given order of magnitude has 90% more probability to be extracted than the numbers in the order of magnitude directly above.
Because of that, on a practical level, he will "almost certainly" extract a number from a reasonably finite sample.
On the other side there is another extraction that is of the player that must participate in the game. If you suppose that he extracts a number to decide which turn he will play in, then the rules that he must follow are exactly reversed: any number must have 90% more probability to be extracted than the number directly below.
This makes it an impossible extraction on all practical levels, and probably logical too.
|
986e2612b8f4aea48697dffb131b1c9e821d41780f3b24399ec2cb81f8615915 | ['91c257166e9d424cb1927af5c59d85e3'] | I need some help.
I have the variable $result.
If I print it, I will have:
echo "<PRE>";print_r($result);
stdClass Object
(
[return] => Array
(
[0] => stdClass Object
(
[field1] => value1
[field2] => value2
[field3] => value3
)
[1] => stdClass Object
(
[field1] => value1
[field2] => value2
[field3] => value3
)
etc...
I need to use a foreach in order to print field by field, for example:
foreach ($result as $key)
echo $key->field1;
But it doesnt work...
How I can do this?
Thanks
| 6b2d306b1849800f927b3811d3cacb801cab495c8c8ca62fd27e2e0c67ece6e1 | ['91c257166e9d424cb1927af5c59d85e3'] | I have a problem with a template with AngularJS.
The page shows a books list with a checkbox. This is used for batch actions, like delete the books. If the list is too long, the books will be shown in a paged list
The problem is, if I check some of them and change the page number, the checkbox will be checked in the same position.
Is easier to understan with this screenshots
I check the first and the third result:
https://i.stack.imgur.com/NK5jE.jpg
Click on the next page:
https://i.stack.imgur.com/GEuMc.jpg
Distinct pages and results, same checked checkbox
The get this results I´m using a query in a action.class.php and sending the json like this:
$ejemplares = array();
foreach($data as $ejemplar_bd)
{
$id_documento = $ejemplar_bd['id_registro'];
$ejemplar = array();
$ejemplar['id'] = $ejemplar_bd['id'];
$ejemplar['idDoc'] = (int)$ejemplar_bd['id_registro'];
$ejemplar['numregistro'] = (int)$ejemplar_bd['numregistro'];
$ejemplar['codigo'] = $ejemplar_bd['codigoejemplar'];
$ejemplar['estado'] = $ejemplar_bd['estado'];
$ejemplar['signatura'] = $ejemplar_bd['signatura1']."-".$ejemplar_bd['signatura2']."-".$ejemplar_bd['signatura3'];
$ejemplar['tipo'] =$ejemplar_bd['tipoejemplar'];
$ejemplar['reservas']=$ejemplar_bd['reservas'];
$ejemplar['Ubicacion']=$ubicaciones[$ejemplar_bd['id']];
$ejemplar['Motivo']=$ejemplar_bd['motivo_expurgado'];
$ejemplar['Editorial']=$data_editorial['valor'];
$ejemplar['Imprimido']= $ejemplar_bd['imprimido'];
$ejemplar = array_merge($ejemplar,$fondos[$id_documento][$ejemplar['id']]);
$ejemplares[] = $ejemplar;
}
$this->json_data = json_encode($ejemplares);
After that, the code in the template is:
<tr ng-repeat="item in data| filter:Buscar | filtroNumregistro:numregistro | filtroCodEjemplar:codEjemplar | filtroNombreNormalizado:nombreFiltro | orderBy:sort:reverse | limitTo: (currentPage - 1) * pageSize - filtrados.length | limitTo: pageSize track by $index">
<td class="sf_admin_text sf_admin_list_td_nombre">
<input type="checkbox" name="ids[]" value="{{ item.id }}" class="sf_admin_batch_checkbox">
</td>
<td class="sf_admin_text">
{{ item.codigo }}
</td>
<td class="sf_admin_text">
{{ item.numregistro }}
</td>
<td class="sf_admin_text sf_admin_list_td_titulo">
<span><a ng-href="{{cambiarUrlTitulo(item.id)}}">{{ item.Titulo }}</a></span><br/>
<span class="autorListEjemplar" ng-repeat="autor in item.Autor">{{autor}}{{$last ? '' : ' - '}}</span>
</td>
<td class="sf_admin_text" style="width:10%;">
{{ item.ISBN }}
</td>
<td class="sf_admin_text" style="width:10%;">
{{ item.Editorial }}
</td>
<td class="sf_admin_text" style="width:10%;">
{{ item.Ubicacion }}
</td>
<td class="sf_admin_text" style="width:10%;">
{{ item.signatura }}
</td>
<td class="sf_admin_text">
{{ item.tipo }}
</td>
</tr> etc...
What is going on?
What could be the problem?
Thanks in advance
|
c3d993aa7f95d5b7229d1f10be5fc091dc793ab3d14ded142a8540b535ac68cf | ['91c8861aaa9640ec8a27ee88e221be32'] | Why don't you simply embed your elements in a container ?
<div id="map"></div>
<div id="filtersContainer">
<div id="distanceFilterContainer">
<input type="checkbox">. . <input type="checkbox">
</div>
<div id="elevationGainFilterContainer">
<input type="checkbox">. . <input type="checkbox">
</div>
</div>
<script>
// ...
var filtersContainer = L.control({position:'topleft'});
filtersContainer.onAdd = function(mymap){
this._div = L.DomUtil.get('filtersContainer')
return this._div
}
filtersContainer.addTo(map)
</script>
| 6b281863cd8daff02276606785e89278c804d4b73cefb981b7966b91b3d6e26c | ['91c8861aaa9640ec8a27ee88e221be32'] | You're restoring your context in each iteration but you don't save it.
Try to add a ctx2.save() and it will work.
for (; i < detector.blades.length; i++) {
ctx2.save(); // save the context
ctx2.strokeStyle = "#000000";
ctx2.translate(initialX, initialY);
ctx2.rotate(rotation);
ctx2.strokeRect(0, 0, thick, y / 2);
ctx2.restore()
// this is the only variable in that changes of
// value in the loop
initialX = margin + thick + initialX
}
|
0a9315ca6ff8c1a2cde1261006cccd77184d7c1d3d9b0a2a975770561b6d22ab | ['91eb642b050d42e88504e3eba7434310'] | I am creating a macro in my PERSONAL.xlsb workbook so that it can be used across all my workbooks.
The macro takes information from workbook 1, copies it into workbook 2, and then takes new information from workbook 2 and puts it into the new worksheets i create in workbook 1.
I am stuck at the part where i want to add multiple sheets to my workbook.
I thought this was simple but i have tried a number of ways to add sheets to my workbook but i keep receiving errors. I tried to create a simple macro that only added sheets but i kept receiving errors for this one line of code.
What do i need to do in order to add worksheets to my workbook?
' Attempt 1: Doesn't work - Run-Time error 1004
ActiveWorkbook.Sheets.Add After:="Sheet23"
' Attempt 2: Doesn't work - Run-Time error 1004
Sheets.Add After:="Sheet23"
'Attempt 3: Doesn't work - Run-Time error 1004
Sheets.Add After:=Sheet23
'Attempt 4: Doesn't work - Run-Time error 1004
Worksheets.Add after:=Sheet23
Desired output (basic): I want to add a new worksheet after sheet 23 in my workbook
Desired output (ideal): I want to add a number of worksheets after sheet 23 according to the number of entries that i have in my list. Each item in the list is numbered from 1 onwards. Each new worksheet should be named according to this number.
| 60f89fa1b0bcba7b5e891d2c6beef394d33399142cba701fce41b34c0777041b | ['91eb642b050d42e88504e3eba7434310'] | I have 18 csv files, each is approximately 1.6Gb and each contain approximately 12 million rows. Each file represents one years' worth of data. I need to combine all of these files, extract data for certain geographies, and then analyse the time series. What is the best way to do this?
I have tired using pd.read_csv but i hit a memory limit. I have tried including a chunk size argument but this gives me a TextFileReader object and I don't know how to combine these to make a dataframe. I have also tried pd.concat but this does not work either.
|
2fcdee8ff9925b87dcc31afd6809ff8c4aebccd3658bf3fd467a03d5db5162f5 | ['91f00fcd1e4f441f9a5b73448c557b5c'] | It is generally possible to have many h1 tag, but structurically it may be better if you have only one h1. You can modify your headers h1's font-size with CSS if you have it inside something, like header tag. Like that:
HTML:
<header>
<h1>My awesome page!</h1>
</header>
<h1>Thing I want to talk about today</h1>
CSS:
header h1 {
font-size: 1.5em;
}
| e61723bb1d0cb92ce6e4100d60d8fa474d1efa95ac9c58c9059886ae32abc9bd | ['91f00fcd1e4f441f9a5b73448c557b5c'] | For me, auto-injecting DebugBar\DebugBar as suggested by my IDE did not automatically work, but gave this error. Changing it to Barryvdh\Debugbar\Facade as DebugBar solved the problem. Seems that there is a totally different package named "DebugBar" installed in the default Laravel configuration.
So, if in the beginning of file you see:
use DebugBar\DebugBar;
Change it to:
use Barryvdh\Debugbar\Facade as DebugBar;
Also, if registered as a facade, you can always use \DebugBar<IP_ADDRESS>addMessage('This is a message'); etc. without injecting it first, as you have told Laravel how to resolve the class. This way you need not to use it first.
|
8e4a358143fa02629ab2a88178dac66310c3b45fd948fb11a1bc0c94ce8ea3df | ['91f2af8f56ca4bbb8eae8df1e0c87f4d'] | I had a knowledge base software program installed on my site located in /kb/
I have installed a new program located in /tech/knowledgebase/
All of the URLs generated by the old program are dynamic and look like:
kb/questions/846/2014+Corvette%3A+GM+TechLink+Article%3A+Heated+Seat+May+Turn+Off
and another example:
kb/questions/841/2014+Corvette%3A+GM+TechLink+Article%3A+Blank+Touch+Screen+after+Start-up+and+in+Reverse
I want to use .htaccess to permanently redirect all of these dynamic links to just /tech/knowledgebase/index.php
I've tried several different redirects within .htaccess, but nothing seems to work. It rewrites part of the path, but can't seem to handle the keywords spilled into part of the url.
Is there a solution for this?
| 7d069fa73f18279471bb5435049d4fbc94eeac068d44d8ca113c21358808082a | ['91f2af8f56ca4bbb8eae8df1e0c87f4d'] | I've basically exhausted myself searching Google and trying to address an error I get when compiling ffmpeg-php on a CentOS / 6.4-64 with PHP 5.4.20 and Apache v2.2.25 (cgi-fcgi).
I end up getting the following when trying to compile. Does anyone have any ideas on how to fix/address this?
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:311: error: âlist_entryâ undeclared (first use in this function)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:311: error: (Each undeclared identifier is reported only once
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:311: error: for each function it appears in.)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:311: error: âleâ undeclared (first use in this function)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:346: error: expected â;â before ânew_leâ
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:356: error: ânew_leâ undeclared (first use in this function)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c: In function âzim_ffmpeg_movie_getCommentâ:
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:531: warning: âcommentâ is deprecated (declared at /usr/local/include/l ibavformat/avformat.h:760)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:531: warning: âcommentâ is deprecated (declared at /usr/local/include/l ibavformat/avformat.h:760)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c: In function âzim_ffmpeg_movie_getTitleâ:
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:546: warning: âtitleâ is deprecated (declared at /usr/local/include/lib avformat/avformat.h:757)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:546: warning: âtitleâ is deprecated (declared at /usr/local/include/lib avformat/avformat.h:757)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c: In function âzim_ffmpeg_movie_getAuthorâ:
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:561: warning: âauthorâ is deprecated (declared at /usr/local/include/li bavformat/avformat.h:758)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:561: warning: âauthorâ is deprecated (declared at /usr/local/include/li bavformat/avformat.h:758)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c: In function âzim_ffmpeg_movie_getCopyrightâ:
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:575: warning: âcopyrightâ is deprecated (declared at /usr/local/include /libavformat/avformat.h:759)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:575: warning: âcopyrightâ is deprecated (declared at /usr/local/include /libavformat/avformat.h:759)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c: In function âzim_ffmpeg_movie_getAlbumâ:
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:590: warning: âalbumâ is deprecated (declared at /usr/local/include/lib avformat/avformat.h:761)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:590: warning: âalbumâ is deprecated (declared at /usr/local/include/lib avformat/avformat.h:761)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c: In function âzim_ffmpeg_movie_getGenreâ:
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:604: warning: âgenreâ is deprecated (declared at /usr/local/include/lib avformat/avformat.h:764)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:604: warning: âgenreâ is deprecated (declared at /usr/local/include/lib avformat/avformat.h:764)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c: In function âzim_ffmpeg_movie_getTrackNumberâ:
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:619: warning: âtrackâ is deprecated (declared at /usr/local/include/libavformat/avformat.h:763)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c: In function âzim_ffmpeg_movie_getYearâ:
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:632: warning: âyearâ is deprecated (declared at /usr/local/include/libavformat/avformat.h:762)
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c: In function â_php_read_av_frameâ:
/usr/local/src/ffmpeg-php-0.6.0/ffmpeg_movie.c:1215: warning: âavcodec_decode_videoâ is deprecated (declared at /usr/l ocal/include/libavcodec/avcodec.h:3656)
make: * [ffmpeg_movie.lo] Error 1
|
2816d36c1e2d42d8d8b6d0e3cfd0ff44fc2fcb8d79fe9cd9576fb4040565f32e | ['9205785bc26c4dba88b67b894fb70b68'] | It is well known that category $\mathcal{Cat}$ of small categories has all small limits and colimits. In particular it has all iverse limits.
I am wondering if there is an explicit constraction of an inverse limit of an inverse system of small categories $$\mathcal C_1\leftarrow\mathcal C_2\leftarrow\cdots $$ like for sets or topological spaces.
I think that it could be a category where objects would be the elements of the limit of this inverse system considered as limit in sets. Functors would be considered as the functions in this case (we forget about the morphisms). And the morphisms between two threads $(A_1,A_2,\ldots)$ and $(B_1,B_2,\ldots)$ would be $(f_1,f_2,\ldots)$ where $f_i:A_i\to B_i$ is a morphism in $\mathcal C_i$ for each $i\in\mathbb N_{+}$.
Am I right?
| 8cb4d55087073bc6bcff154da86114832b0d4adbe9aa1f5b1fb711040063540d | ['9205785bc26c4dba88b67b894fb70b68'] | Recently I have found such a thing like ,,finite boolean combination of open sets" (of a topological space). Unfortunatlety I haven't found anywhere the precise definition of such combination.
Does anyone know where could I find it?
The only thing that I can figure out myself is connected with the boolean algebra of sets where we have three operations: union, intersection and complement of sets. Is this combination a set that we can get using intersections (of two sets), unions (also of two sets) and complement operations applied finitely many times to the mentioned family of open sets? Am I right?
|
0cb23071c05354b273c6f35f13622fbb5285fa2e650b2f886d631f01e7e76a51 | ['9213364db0a14a78b23b6dc9058cb823'] | Nice answer! Thank you so much. Just to ensure more, do you mean that if $M_1$ and $M_2$ are two inequivalent irreducible $FG$-modules then $M_1=N_1\bigoplus L_1$ and $M_2=N_2\bigoplus L_2$ as $\overline{F}G$-modules, which $N_1$ is not isomorphic to $N_2$ as an $\overline{F}G$-module because $M_1$ is not isomorphic to $M_2$ as an $FG$-module? Would you please explain this part a little more? | b43eda217b2c75548b33eb16b90a83c7bff377587b6820ef6b315a1fde86e742 | ['9213364db0a14a78b23b6dc9058cb823'] | I am trying to solve an exercise from the book "Permutation Groups" by <PERSON> and <PERSON>, but, this is not a homework.
The affine geometry $AG_d(F)$ consists of points and affine subspaces constructed from the vector space $F^d$ of row vectors of dimension $d$ over the field $F$. The points of the geometry are the vectors of $F^d$ and the affine subspaces are the translates of the vector spaces of $F^d$. Thus if $W$ is a $k-$dimensional subspace of $F^d$, then $W+v=\{w+v:w\in W\}$. My question is about the following exercise, where $AGL_d(F)=\{t_{a,v}:u\mapsto ua+v \mid a \in GL_d(F),v\in F^d\}$:
For solving this exercise, if $\Sigma$ be the set of all affine bases, I defined the action of $AGL_d(F)$ on $\Sigma$ as follows:
$$B^{t_{A,v}}=\{(\alpha_0)A+v,\ldots, (\alpha_d)A+v \}$$ It is easy to see that this action is well-defined. Then I tried to prove that this action is transitive and regular, but despite my attempts, I could not.
Also, I tried to construct an example of an affine basis for $AG_d(F)$ to understand the definition better, but I could not too.
I appreciate for your help.
|
587406e90d699426ecc84ac287e07fc1265cc6894ba5f342d235c6c7e57b8166 | ['92136b54fe7646e6a90855aa769f9a0c'] | This problem could be resolved easily by following commands
Go to terminal mode by CTRL + ALT + F3 and login then
sudo apt install --reinstall ubuntu-desktop
sudo apt install --reinstall ubuntu-session
If it does not work, try as follow:
chown $USER:$USER .Xauthority
or try to rebuild .Xauthority
mv .Xauthority .Xauthority.bak
| 1acb8748320344edc87e510b46fb98ad83fa1bd5c524bf9256359404cee4549f | ['92136b54fe7646e6a90855aa769f9a0c'] | I installed icecast2 for broadcasting ( online radio). But complexity on its settings did suffered me. I want to remove it completely. I tried with sudo apt-get purge icec* system was start to delete unrelated files, and I stopped it with CTRL+C. So my Ubuntu desktop had gone and I reinstalled unity-2d again.
How can I remove this program and its plugins without affecting other programs?
|
33530b56255ef9a9e485562ef886831f44615839d560adc84bae7a50d8c7daad | ['922ab5d0d4cc466caab6098d814e4199'] | You can use .loc to filter based on a series.
def complex_filter_criteria(x):
return x != 1111
df.loc[df['account_no'].apply(complex_filter_criteria)]
df['account_no'].apply(complex_filter_criteria) will return a series of True/False evaluations for each entry in the column account_no. Then, when you pass that into df.loc, it returns a dataframe consisting only of the rows corresponding to the True evaluations from the series.
| e1b4ba8c34ceabac1d7afaf2cecc54072b192f8ac4c704facb0adc7612dbe4fc | ['922ab5d0d4cc466caab6098d814e4199'] | You're using the ready callback, so all of this runs when the DOM is ready. However, you don't actually create the new button until this ready callback has already run! So when you try to add callbacks with $("button").click(function(){}), you are trying to add that callback to all the buttons on the DOM... but some of the buttons you want to add it to do not exist yet. They won't exists until that first button's click callback is executed! So the first button you make will have the callback attached, but the new ones will not.
Maybe try something like this? I expect something will be wrong with how the value of this works on your click callback, but I think it's a nudge in the right direction.
$(document).ready(function () {
$("#btnAddSubmit").click(function () {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
// be wary of what the value of `this` refers to! it might refer to
// the `this` of the scope in which it was defined!
function gifCallback() {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
currentGif = currentGif.toLowerCase();
var topicNum = topics.indexOf(currentGif);
var myUrl = "https://api.giphy.com/v1/gifs/search?q=" + topics[topicNum] + "&api_key=oaPF55NglUdAyYKwDZ0KtuSumMrwDAK9&limit=15";
$.ajax({
method: "GET",
url: myUrl,
}).then(function (response) {
console.log(currentGif);
console.log(response);
$("#gifLocation").empty();
var gifURL = response.data[0].images.fixed_width.url;
console.log(response.data.length);
var gifNum = response.data.length
for (var i = 0; i < gifNum; i++) {
$("#gifLocation").append('<div id=gifDiv' + i + '></div>');
gifURL = response.data[i].images.fixed_width.url;
var gifRateId = "gifRate" + i;
var ratingLocString = '<p id="' + gifRateId + '"></p>'
var ratingLoc = $(ratingLocString);
var rating = response.data[i].rating;
var gifRating = "Rating: " + rating;
$("#gifDiv" + i).append(ratingLoc);
$("#" + gifRateId).text(gifRating);
var gifId = "gif" + i;
var gifImage = $('<img class=gif id=' + gifId + '>');
gifImage.attr("src", gifURL);
$("#gifDiv" + i).append(gifImage);
}
});
console.log(currentGif);
}
};
// reference the new button by its ID and add your desired callback
$("#gif").click(gifCallback)
});
});
|
ae9ebc53a0656353577a411a3805adf3bf0cf2c3caeee3186ed8e60a364b6922 | ['922f86a8e5664d9583d9d9e38b0d3d73'] | You must enable virtualization technology.
1.go to control panel
2.go to programs and features
3.click on "turn windows feature on or off" a prompt box will be appear()
4.unmark the checkbox of Hyper-v.
As shown below:
restart your system and press the delete button.
You have to go to bios.
You should look in the BIOS to follow one of the following options to enable them.
Intel Virtualization Technology.
Intel VT-x.
Virtualization Extensions.
Vanderpool.
| 3e84b694eb9f61883a9288615ea4bebb5b43c126da7f18b0eb75fe25dd442ae6 | ['922f86a8e5664d9583d9d9e38b0d3d73'] | I have a database of numbers that its users on the app store.
I want to get a SMS that comes only from these numbers.
Basically what I should do?
Please help me.Thank you.
DatabaseHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "PhoneNumber.db";
public static final String TABLE_NAME = "number_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NUMBER INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String number){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,number);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public ArrayList getAllrecord(){
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from admin", null);
res.moveToFirst();
while (res.isAfterLast()== false){
array_list.add(res.getString(res.getColumnIndex("number")));
res.moveToNext();
}
return array_list;
}
ReceiveMessage:
public class ReceiveMessage extends BroadcastReceiver {
final SmsManager mysms = SmsManager.getDefault();
@Override
public void onReceive(Context context, Intent intent) {
Bundle mybundel = intent.getExtras();
try {
if(mybundel !=null){
final Object[] messageContent=(Object[])mybundel.get("pdus");
String smsMessageStr = "";
for (int i=0;i<messageContent.length;i++){
SmsMessage mynewsms = SmsMessage.createFromPdu((byte[]) messageContent[i]);
NewMessageNotification nome = new NewMessageNotification();
nome.notify(context,mynewsms.getDisplayOriginatingAddress(),mynewsms.getDisplayMessageBody(),i);
i++;
String smsBody = mynewsms.getMessageBody().toString();
String address = mynewsms.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";
}
Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();
//this will update the UI with message
SmsInbox inst = SmsInbox.instance();
inst.updateList(smsMessageStr);
}
}
catch (Exception ex){
}
}
smsInbox:
public class SmsInbox extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemClickListener {
private static SmsInbox inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;
public static SmsInbox instance() {
return inst;
}
@Override
public void onStart() {
super.onStart();
inst = this;
}
DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_inbox);
smsListView = (ListView) findViewById(R.id.SmsList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, smsMessagesList);
smsListView.setAdapter(arrayAdapter);
smsListView.setOnItemClickListener(this);
if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) {
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://sms/inbox"), null, null,
null, null);
int indexBody = cursor.getColumnIndex("body");
int indexAddr = cursor.getColumnIndex("address");
if (indexBody < 0 || !cursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = "SMS From: " + cursor.getString(indexAddr) +
"\n" + cursor.getString(indexBody) + "\n";
arrayAdapter.add(str);
} while (cursor.moveToNext());
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
toggle.setDrawerIndicatorEnabled(false);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void updateList(final String smsMessage) {
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
try {
String[] smsMessages = smsMessagesList.get(pos).split("\n");
String address = smsMessages[0];
String smsMessage = "";
for (int i = 1; i < smsMessages.length; ++i) {
smsMessage += smsMessages[i];
}
String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menuRight) {
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
drawer.openDrawer(Gravity.RIGHT);
}
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.Home_page) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.not_pay) {
if (SmsInbox.this.drawer != null && SmsInbox.this.drawer.isDrawerOpen(GravityCompat.END)) {
SmsInbox.this.drawer.closeDrawer(GravityCompat.END);
} else {
Intent intent = new Intent(this, MainActivity.class);
SmsInbox.this.startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
} else if (id == R.id.date_pay) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.bill_sms) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.help_menu) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.for_us) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.exit_app) {
finish();
overridePendingTransition(0, 0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.END);
return true;
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
Database table :
|
a0036bdc7973a1155c76fb64844bc2600df99652357f1fbd901f4e0528948ddd | ['9233afa79e3341db94abc8a52564f26d'] | Use form and <input type="url"> to validate it. The form can only be submitted with the valid value(s).
$('form').on('submit', function(e){
e.preventDefault();
console.log('valid URL');
});
<form>
Input a URL: <input type="url" required><br>
<input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
| af538fb202febc771e5937bbb631da10f2c931a922c49fe4a38a50627b0c45d8 | ['9233afa79e3341db94abc8a52564f26d'] | TL;DR Simply calculate again.
Your calculate way is already good, just wrap it with a function, and then you can call it whenever you want to.
function addMore() {
var new_raw = $('<tr><td><a href="javascript:void(0);" style="padding:0px;" class="remove">Remove</a><td><input type="number" class="addData"></td></tr>');
new_raw.insertBefore('#my_new_raw');
$("#myTable").on('click', '.remove', function() {
$(this).parent().parent().remove();
calculate();
});
}
function calculate() {
var sum = 0;
$('.addData').each(function(i) {
if (!isNaN(this.value) && this.value.length != 0) {
if ($(this).hasClass('addData')) {
sum += parseFloat(this.value);
}
}
});
$('#my_total').val(sum.toFixed(2));
}
$(document).on('blur keyup', '.addData', function(e) {
calculate();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="myTable">
<tbody>
<tr>
<td>Value 1</td>
<td><input type="number" class="addData"></td>
</tr>
<tr>
<td>Value 2</td>
<td><input type="number" class="addData"></td>
</tr>
<tr id="my_new_raw">
<td><a href="javascript:void(0);" onclick="addMore()">Add More</a></td>
<td></td>
</tr>
<tr>
<td>Total</td>
<td><input type="number" readonly id="my_total"></td>
</tr>
</tbody>
</table>
|
ccfe960330d5c891d4bbdeb3769e2691436a968a64ae65fae3896c9dd0b911b7 | ['9233ddff20004871949c848d41fea17a'] | If I have four different value cards, what is the probability that the lowest card (ace, lowest -> king, highest) is some value X?
Here is what I have so far:
I know that the lowest value card cannot be a king, queen, or jack, as there must exist a value that is 3 above. And I can guess that the probability of an ace will be the highest and a 10 will be the lowest. Can someone please give me some hints on how I should approach this?
| 90ddd0354b07fe802027859c52daf618ffe799d9a9fba1cec99ae7e4512b079e | ['9233ddff20004871949c848d41fea17a'] | You can do this without referencing any table except Office Locations by manually entering SQL code in the SQL view for a query (you don't even put anything in the design view first, just create a blank query and go to SQL view). You use a self join enabled by aliases:
SELECT a.Company, a.Country
FROM [Office locations] as a
INNER JOIN
(SELECT Company
FROM [Office locations]
WHERE Country = 'India') as b
ON a.Company = b.Company
GROUP BY a.Company
HAVING COUNT(DISTINCT a.Country) > 1
This will return all companies that have an office in India that also have an office in at least one other country. If you just want the companies that have offices in more than one country, regardless of whether one of those countries is India you'd use:
SELECT Company, Country
FROM [Office locations]
GROUP BY Company
HAVING COUNT(DISTINCT Country) > 1
|
fb81570084ebbc78eca841a4dc7b651ed97f5c91ca0cde8774ce297a61411a54 | ['9238d5449d6044c999c0101ee1958e1b'] | Recently I've become more interested in the topic of the stability of planetary systems. I have been reading about it and it seems that orbital resonances play an important role in the stability of Solar System (as well as in the moons of Jupiter and other planets).
I first thought that the orbital resonance is somehow more stable and thus we have several cases in the Solar System.
But as I kept reading, I found out that in the asteroid belt there were some gaps precisely where the resonances happen, so the resonances are actually instable for asteroids.
I then thought that some resonances are stable while others are instable, but some of the resonances that makes gaps in the asteroid belt are actually present in the Solar System between planets, so I am completely lost.
Why resonances are sometimes stable and sometimes instable? What am I missing?
Maybe I am misunderstanding something because it doesn't make sense to me. Any help will be welcome.
| 73af11fb7147b0955eebfc446913c916ed3f20349ad32caaeda5094bec4e4cfa | ['9238d5449d6044c999c0101ee1958e1b'] | Well, seeing as you are interested in the actual nuts and bolts of the Debian package system, this is probably the page for you: From the Debian Docs
This also seems like a good introduction: Presentation on Apt and Dpkg
Of course Wikipedia is also a fabulous source for an overview as always : Advanced Package Tool
The bottom line it seems is that using only "raw" dpkg, it is quite possible to get stuck in RPM-like dependancy hell. dpkg provides only a framework for writing, distributing and executing pre/make/post scripts for installation.
Aptitude or the "Advanced Packaging Tool" provides a layer of abstraction above the dpkg system which allows for more advanced and useful functionality such as dependency and "recommends" resolution.
So by using apt you are far less likely to shoot yourself (and/or your system) in the foot and you will almost never need to muck with dpkg.
|
6a5e436931ebd13edcafddd19fcc514e70c3fbeffbfb4b42d87caa0673061e0e | ['9244b470755d48959d629888d1ada1ac'] | Let $f:S^n\rightarrow S^n$ be of odd degree, i.e. $f^*(1)$ is odd where $f^*:H_n(S^n)\rightarrow H_n(S^n)$ is the induced map on homology. Prove that there exists an $x\in S^n$ with $f(-x)=-f(x)$.
I tried to imitate the proof of Borsuk-Ulam theorem, but with no achievements.
Even in the case of $S^1$, I can not see how this happens, mainly because I don't know how to turn the condition on homology to some more intuitive ones. Should I use alternative definition of degrees in this case?
| 7b5fe1e78090f04b706b0eb651d9b7c240d70264908dc2538eea814eee4cdb49 | ['9244b470755d48959d629888d1ada1ac'] | Independente da forma que eles são, é dúvida é como essa app irá fazer essas duas rotas, como eu posso ir na barra superior digitar /form ele ir para o formulário ou eu digitar /login ele ir para uma página totalmente distintas, sendo que isso é só um exemplo já que isso pode ser para outra app totalmente diferente, você pode se basear no WordPress que você tem uma rota para a administração e outra para a página do site sendo que no site não há nem um botão para ir para a página de administração (na maioria das vezes) |
e4925ceb397ebf839043c1a2be86f8446164cb4bd911727f08e9fc189eabd018 | ['924cafbc5dd848f29821f20c29ceee53'] | hi every one i have list of dictionary all of the dictionaries like this:
dict1 = {Label:----,Chapter:----,Section:----,Massage:----}
dict2 = {Label:----,Chapter:----,Section:----,Massage:----}
dict3 = {Label:----,Chapter:----,Section:----,Massage:----}
List = [dict1 , dict2 , dict3]
i want first the all dictionaries of list if the my label is equal with label in dictionary print the massage of that dictionary.
i use this method but it get nothing.
def printMassage(List , mylabel):
for dicts in List:
if (Label.value == mylabel):
print( Massage.value)
please help me!!
| d135db6f35f67a4f9b00ed430cffc6a95950f19e754e8480676df3a0be0b3b45 | ['924cafbc5dd848f29821f20c29ceee53'] | i want save input that i get from user and save them in element .
i want to access elements that user write in my UI.
and if i want save the elements in array list which kind of array list i should build.
in my UI i have text field name and text field middle name and combo box city has got 3 city name and and a radio box that it depend sex.
in final show them in console what should i do ?
this all of my code:
package ui;
import java.awt.*;
import javax.swing.*;
public class UI extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(500, 600);
BorderLayout blayout = new BorderLayout();
JButton center = new JButton();
JButton north = new JButton();
JButton south = new JButton();
JComboBox combo = new JComboBox();
combo.addItem("-");
combo.addItem("Tehran");
combo.addItem("Tabriz");
combo.addItem("Shiraz");
JRadioButton rb1 = new JRadioButton("man");
JRadioButton rb2 = new JRadioButton("weman");
frame.setLayout(blayout);
FlowLayout fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
JLabel jb1 = new JLabel("Name :");
JTextField name = new JTextField(20);
center.add(jb1);
center.add(name);
JLabel jb2 = new JLabel("Family :");
JTextField family = new JTextField(20);
center.add(jb2);
center.add(family);
JLabel jb4 = new JLabel("City :");
center.add(jb4);
center.add(combo);
JLabel jb5 = new JLabel("Sex :");
center.add(jb5);
center.add(rb1);
center.add(rb2);
JLabel jb6 = new JLabel("Comment :");
JTextField comment = new JTextField(50);
JLabel jb7 = new JLabel("Save");
south.add(jb7);
JPanel cpanel = new JPanel();
cpanel.add(center);
JPanel spanel = new JPanel();
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
cpanel.add(jb6);
cpanel.add(comment);
frame.add(cpanel,BorderLayout.CENTER);
frame.add(spanel,BorderLayout.SOUTH);
}
}
|
c4f62123a86ef35f235577550bc79c9091f21c814a59a9ca7918a199e07ff511 | ['924d2e4eea5c45199d6beae4f8b9b9ac'] | Oftentimes the cause of this sort of random hibernation/shutdown is overheating. Most computers are set to hibernate if the internal temperature reaches a certain level. A friend of mine has an Asus laptop, and it tends to run hot. Speedfan is a very popular piece of software which can be used to check the temperature being reported by your computer's internal sensors. You should be able to find a datasheet for your CPU, which will tell you the heat tolerances, and whether it is in fact the heat that is causing it to hibernate.
| 19f77842151c214a05d30ca9d983bc449f6625e04629a3615e2826106216d05c | ['924d2e4eea5c45199d6beae4f8b9b9ac'] | Try running CCleaner or a similar program. It will clear up temporary files on your computer, and old, unused registry entries, both of which can slow your computer down. You may want to tell it not to remove cookies. Removing cookies will speed up your computer a bit, but it will also make it so you have to type in your password again on most sites that you've set to remember it.
|
ce88ef55433680a4f12aa74370fa99bceb4922a281bcaafa4c3cdf722356495f | ['924eab2be62942cd8ba5a3a69e6cf617'] | categories = new Ext.data.Store({
model: 'categories',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'http://localhost/php/server.php?action=catall',
reader: {
type: 'json'
}
}
});
its the json data
[{"catname":"HEALTH","id":"1"},{"catname":"IMAGINE","id":"2"},{"catname":"ENTERTAINMENT ","id":"3"},{"catname":"KIDS","id":"4"},{"catname":"LOCAL","id":"5"},{"catname":"TRAVELLER ","id":"6"},{"catname":"INTERNET ","id":"7"}]
| cb07a26ff0be9a8836f3e7575fe38f5455a1b090abcfbaae7c03d9c95e02b700 | ['924eab2be62942cd8ba5a3a69e6cf617'] | If you haven't already found a solution than here is a one of the possible solutions that I found for the this issue. Note this is only if you are using Kali as a virtual machine in virtual box. I couldn't pinpoint the problem, but it seems like the issue is either with the bridge connection or Nat network connection. So just change it to host only adapter and when you boot up use a wifi adapter rather than the Ethernet connection that connect your virtual machine to your host machine. Just use ifconfig command and turn the wired connection off. That should do the trick.
|
b51b6a4a2e0cc1f04dfb9167afce5e351a71e2919c8d0a5cbf61932ffaeb3a0a | ['92570e6ddbf64ee8a6e312b5a661bb58'] | Can someone find all the sub Lie algebra of W_1, or simply Der(F[x]) (derivation Lie algebra of polynomials algebra in one varialbe)?
I think all the sub Lie algebra of Der(F[x]) is the following three types:
(1) dim=1: spanned by
$u\partial_x$ for any $u\in F[x])$;
(2) dim=2: spanned by $x\partial_x, x^2 \partial_x$;
(3) dim=3 spanned by $\partial_x, x\partial_x, x^2\partial_x$.
That is to say dim>4 is imposible. Can you prove it? | d220291d0209beebe2b41f2406ccc0badd65afc3a9cf19e5ca86fa0b9ea18d51 | ['92570e6ddbf64ee8a6e312b5a661bb58'] | this command should get you what you are looking for:
find / -type d -name httpdocs
that will search from the root of your server for directories with the name of httpdocs or if you just want to search from the current directory replace the '/' with a '.'
Another command you can try is locate you would do something like:
locate httpdocs
|
eae0b5f56cd621fffffd06999b86ba5aaeec2cf33fa9dd07a5a1c6273bcf3365 | ['92594648564b41c1a8fbb4956bf6128b'] | I used LDraw long before I learned about TLG's official use of millimeters. At some point on my own I measured a regular baseplate as being (roughly) 10 inches wide. In LDraw one baseplate is 640 units wide. Thus originally (and I still do this today even though I know it's not correct) I visualized the LDraw system as having 64 units per inch, and a 1x1 brick being 5/16 inches wide and 3/8 inches tall (ignoring the gaps between bricks). 1/16 inches happens to be very close to 1.6mm. | 079f8737e073019ecaccb0497b9b1bbfb5bc3a919c97786ae35fbaa761a934c1 | ['92594648564b41c1a8fbb4956bf6128b'] | @TuneerChakraborty This is a basis dependent thing yes. The idea is that each party still has a local freedom to choose the orientation of their system which wont affect the statistics they observe. By using this freedom it would seem that the authors can justify that they need only consider states with real coefficients. |
1738ba90832596a88bacf064d90fe7ee2481e9473ad5478e4e077a907382abab | ['925bc4f1ff6e4b56b0a68661628efcea'] | I am working on another project where i create a gui that has a button to connect to the database, and a button to run a sql command. Problem is that I am trying to use two different methods. one to connect and one to run a command.
Now i did get the code to compile fine, but spawns a runtime error when i go to run a command.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javasql.Javasql.exeCommand(Javasql.java:54)
at javasql.UserInterface.actionPerformed(UserInterface.java:195)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6516)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6281)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4872)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
at java.awt.EventQueue.access$300(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:706)
at java.awt.EventQueue$3.run(EventQueue.java:704)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:720)
at java.awt.EventQueue$4.run(EventQueue.java:718)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Here is my code:
package javasql;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author KJ4CC
*/
import javasql.UserInterface;
import javax.swing.JOptionPane;
public class Javasql {
Connection connection;
ResultSet result;
public static void main(String[] args) {
UserInterface gui = new UserInterface();
gui.startGui();
}
public void connect(UserInterface gui) {
gui.username.setText("client");
gui.pass.setText("Brandy");
try {
String driver = (String) gui.driverSelect.getSelectedItem();
String url = (String) gui.url.getSelectedItem();
Class.forName(driver);
try {
connection = DriverManager.getConnection(url, gui.username.getText(), gui.pass.getText());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Please Check you SQL Command, you may not have the privalges to execute such command!", "Alert", JOptionPane.ERROR_MESSAGE);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Javasql.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Database connected");
}
public void exeCommand(UserInterface gui) {
Statement command;
try {
command = connection.createStatement();
result = command.executeQuery(gui.command.getText());
while (result.next()) {
System.out.println(result.getString("ridername") + " \t");
}
} catch (SQLException ex) {
Logger.getLogger(Javasql.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
ActionListener:
public void actionPerformed(ActionEvent e) {
Javasql sql = new Javasql();
if (e.getSource() == connect){
sql.connect(this);
}else if(e.getSource() == clr){
command.setText("");
}else if(e.getSource() == exeSql){
sql.exeCommand(this);
}
}
}
I was thinking that my
Connection connect;
at the beginning of the code would work as if i had it in a different method. How could i stop this null pointer?
| 58ded7104580c1cb818394b6dbc1734a5dc29c48f19a6cf3f6aa15facd2e1d8a | ['925bc4f1ff6e4b56b0a68661628efcea'] | I am developing a small sql servlet application that takes in a SQL command from a text area in an html page, sends the command to a servlet that makes an sql connection and puts in the resultset into an arraylist. I have all of that down, and i can print column names to the browser in the java servlet class. One thing i need to do is print the results into a table using a JSP page. The JSP page will look just like the html page we first used. I can not figure out how i am going to get the arraylist from the servlet to the JSP page to be displayed to the user.
Here is the HTML page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
</font>
</body>
</html>
and here is the servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
/**
*
* @author KJ4CC
*/
public class NewServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
Connection connection;
Vector<String> columnNames = new Vector<String>();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String command = request.getParameter("command");
out.println("<!DOCTYPE html>");
out.println("<html>");
sqlConnection(command);
//prints out column names into the browser.
out.println(columnNames);
}
}
public void sqlConnection(String command){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/project3";
String user = "root";
String pass = "Brandy?1994";
ResultSet rs;
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connection = DriverManager.getConnection(url,user,pass);
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
Statement stmt;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery(command);
int colNum = rs.getMetaData().getColumnCount();
for (int i = 0; i < colNum; i++) {
columnNames.add(rs.getMetaData().getColumnLabel(i+1));
}
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Here is the start of the JSP page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
<%
DO TABLE STUFF HERE TO OUTPUT SQL RESULTS
%>
</font>
</body>
</html>
I think i will create a javaBean to store the arrays so that the JSP page can access the column arraylist. Then use a for loop to iterate through the array list so that i can create the table columns. how could i link the JSP page to the servlet so that if can get the information needed?
I have to do the sql connection in the servlet and cannnot make the connection in the JSP page.
|
c769e69f3d1d6812bd8a3a28ed776da5b21c687b4ee2c52ab5120794146585f8 | ['925e44c6d01648c69bfc1f422bf39f73'] | What software can be used to graph a triple integral? I tried to use wolfram alpha, but it wouldn't work.
I am trying to graph:$ \int_0^1 \int_\sqrt{z}^1 \int_0^{2-y-z} f(x,y,z) \; \mathrm{dx\; dy\; dz}$
Could anyone graph this for me please, and tell me the used software! Thank you for your help!!!
| 1d830872e477c73eb188311a75aa6ecc749c48ddd44005f43ea7a78c46e752b1 | ['925e44c6d01648c69bfc1f422bf39f73'] | One further question(this may be much harder, I don't know). Is $\forall x, log(x)^4 \lt x$. I am sure it is by doing some computations, since for $x\lt 10$ the power decreases $log(x)^4$, and after that it never gets a chance to catch up.(Note: Here I mean $log_10$, and above I intentionally did mean $ln$ |
be5ba3655ec5926a32516d5ecffd4aa61d960be1cfd2c751c00690194e6e8001 | ['926429f5844842c3a8f3662b868f3230'] | I'm fairly new to redux. I'm taking an E-Commerce site tutorial using React and Redux.
I have a CollectionItem Component that has a button that calls an addItem function which adds the specified item to the shopping Cart.
The addItem function works for CollectionItems Component generated from CollectionPreview however it doesnt work for CollectionItems Components generated from Collections. Whenever the button is clicked i get a TypeError: addItem is not a function.
find codes below
CollectionItem Component
import React from "react";
import "./collection.item.style.scss";
import CustomButton from "../custom-button/custom.button.component";
import { connect } from "react-redux";
import { addItem } from "../../redux/cart/cart.action";
export const CollectionItem = ({ item, addItem }) => {
const { name, imageUrl, price } = item;
return (
<div className="CollectionItem">
<div
className="Image"
style={{
backgroundImage: `url(${imageUrl})`
}}
/>
<div className="footer">
<span className="ItemName">{name}</span>
<span className="ItemPrice">#{price}</span>
</div>
<CustomButton onClick={() => addItem(item)} color="outline-dark">
Add to Cart
</CustomButton>
</div>
);
};
const mapDispatchtoProps = dispatch => ({
addItem: item => dispatch(addItem(item))
});
export default connect(null, mapDispatchtoProps)(CollectionItem);
CollectionPreview Component
import React, { Component } from "react";
import CollectionItem from "../collection.item/collection.item.component";
import "./collection.preview.style.scss";
class Preview extends Component {
render() {
const { title, items } = this.props;
return (
<div className="CollectionPreview">
<h1 className="CollectionTitle">{title}</h1>
<div className="Preview">
{items
.filter((item, index) => index < 4)
.map(item => (
<CollectionItem key={item.id} item={item} />
))}
</div>
</div>
);
}
}
export default Preview;
Collection Component
import React, { Component } from "react";
import "./collection.style.scss";
import { connect } from "react-redux";
import { selectCollection } from "../../redux/shop/shop.selector";
import { CollectionItem } from "../collection.item/collection.item.component";
class Collection extends Component {
render() {
const { title, items } = this.props.collections;
return (
<div className="collection-page">
<h2 className="title"> {title}</h2>
<div className="container items">
{items.map(item => (
<CollectionItem key={item.id} item={item} />
))}
</div>
</div>
);
}
}
const mapPropsToState = (state, ownProps) => ({
collections: selectCollection(ownProps.match.params.collectionId)(state)
});
export default connect(mapPropsToState)(Collection);
Redux Cart Action
import { TOGGLE_CART } from "./cart.types";
import { ADD_ITEMS } from "./cart.types";
import { DELETE_ITEMS } from "./cart.types";
import { INCREASE_QUANTITY } from "./cart.types";
import { DECREASE_QUANTITY } from "./cart.types";
export const toggleCart = () => {
return {
type: TOGGLE_CART
};
};
export const addItem = item => {
return {
type: ADD_ITEMS,
payload: item
};
};
export const deleteItem = item => {
return {
type: DELETE_ITEMS,
payload: item
};
};
export const increaseItem = item => {
return {
type: INCREASE_QUANTITY,
payload: item
};
};
export const decreaseItem = item => {
return {
type: DECREASE_QUANTITY,
payload: item
};
};
Cart Reducer
import { TOGGLE_CART } from "./cart.types";
import { ADD_ITEMS } from "./cart.types";
import { addItemToCart } from "./cart.utils";
import { DELETE_ITEMS } from "./cart.types";
import { deleteItemFromCart } from "./cart.utils";
import { increaseCartItem } from "./cart.utils";
import { decreaseCartItem } from "./cart.utils";
import { DECREASE_QUANTITY } from "./cart.types";
import { INCREASE_QUANTITY } from "./cart.types";
const initialState = {
showCart: false,
cartItems: []
};
const cartReducer = (state = initialState, action) => {
switch (action.type) {
case TOGGLE_CART:
return {
...state,
showCart: !state.showCart
};
case ADD_ITEMS:
return {
...state,
cartItems: addItemToCart(state.cartItems, action.payload)
};
case DELETE_ITEMS:
return {
...state,
cartItems: deleteItemFromCart(state.cartItems, action.payload)
};
case INCREASE_QUANTITY:
return {
...state,
cartItems: increaseCartItem(state.cartItems, action.payload)
};
case DECREASE_QUANTITY:
return {
...state,
cartItems: decreaseCartItem(state.cartItems, action.payload)
};
default:
return state;
}
};
export default cartReducer;
| e96770640d2578dd91106dcfd929c59961ba2d1e3471b6f48a0a80185a7ff39c | ['926429f5844842c3a8f3662b868f3230'] | Use a grid for the outer container and set grid-template-columns to repeat(7, 1fr) and grid-template-rows to whatever height you want. This should prevent wrapping.
You cannot keep the images and grid size fixed with a min height of 400 and min width of 320 as this will affect the responsiveness when viewed on a smaller screen size. Will advice you make the image responsive thus it adjusts to fit the size of its container.
|
44c958d12c422d2080e810a7d0d9154a748b2ee73111784e5079284603b9e2bc | ['927bb76a02dd419789548374e9c790bf'] | What helped was to add this in viewController with largeTitles enabled:
override func viewWillAppear(_ animated: Bool) {
let navigationBack = UIView()
navigationBack.frame = (self.navigationController?.navigationBar.frame)!
navigationBack.frame.size.height = 44
navigationBack.backgroundColor = navigationController?.navigationBar.barTintColor
let containerView = transitionCoordinator?.containerView
transitionCoordinator?.animateAlongsideTransition(in: containerView, animation: { (context) in
containerView?.addSubview(navigationBack)
navigationBack.frame.size.height = (self.navigationItem.searchController?.searchBar.frame.height)! + (self.navigationController?.navigationBar.frame.height)!
}, completion: { (context) in
navigationBack.removeFromSuperview()
})
super.viewWillAppear(animated)
}
and this in viewController with largeTitles disabled:
override func viewWillAppear(_ animated: Bool) {
let navigationBack = UIView()
navigationBack.frame = self.navigationController?.navigationBar.frame ?? CGRect.zero
navigationBack.backgroundColor = navigationController?.navigationBar.barTintColor
let containerView = transitionCoordinator?.containerView
transitionCoordinator?.animateAlongsideTransition(in: containerView, animation: { (context) in
containerView?.addSubview(navigationBack)
navigationBack.frame.size.height = 44
}, completion: { (context) in
navigationBack.removeFromSuperview()
})
super.viewWillAppear(animated)
}
| 2f06b58ca329da79612b9ff087370a7b324bb19fc5a19fbb151da488f96948bf | ['927bb76a02dd419789548374e9c790bf'] | Updated to Swift 4
Swift 4:
if let parentVC = self.parent {
if parentVC is someViewControllerr {
// parentVC is someViewController
} else if parentVC is anotherViewController {
// parentVC is anotherViewController
}
}
Swift 3:
if let parentVC = self.parentViewController {
if let parentVC = parentVC as? someViewController {
// parentVC is someViewController
} else if let parentVC = parentVC as? anotherViewController {
// parentVC is anotherViewController
}
}
|
318a39b78f15c7beb72e13db17bab062ba39e7b48fadbae18ddc0fb6ef1e8cfa | ['927d6856306a4929a97d65ff97ff0dee'] | xml sample
<?xml version="1.0" encoding="UTF-8"?>
<CUSTOMERS xml:lang="en">
<CUSTOMER CREATED_DATE="2020-10-16 13:21:09.0" GROUP_ID="" ID="1509999">
<NAME>
<TITLE></TITLE>
<FIRST_NAME>John</FIRST_NAME>
<LAST_NAME>Smith</LAST_NAME>
</NAME>
<GENDER/>
<DATE_OF_BIRTH/>
<CONTACT_DETAILS>
<TELEPHONE MARKETING_OPT_IN="F" TYPE="MOBILE">0123456789</TELEPHONE>
<EMAIL MARKETING_OPT_IN="F"><EMAIL_ADDRESS></EMAIL>
</CONTACT_DETAILS>
<ATTRIBUTE NAME="theCompany-News and offers on theCompany Womenswear_OPT_EMAIL">T</ATTRIBUTE>
<ATTRIBUTE NAME="Email Soft Opt In_OPT_EMAIL">F</ATTRIBUTE>
<ATTRIBUTE NAME="REGISTERED_ON_WEBSITE">T</ATTRIBUTE>
</CUSTOMER>
</CUSTOMERS>
I have inherited an Azure Powershell function which builds a list of values from XML file.
I need to add some code to access this value:
<ATTRIBUTE NAME="Email Soft Opt In_OPT_EMAIL">F</ATTRIBUTE>
This is the Powershell Code I have so far
[xml]$xml = Get-Content C:\Users\Jason2\Desktop\XMLfolder\theSample.xml
$xml
$CustomerListFull = @()
foreach ($customer in $xml.CUSTOMERS.CUSTOMER)
{ $BuildList = New-Object -TypeName psobject
$BuildList | Add-Member -MemberType NoteProperty -Name TITLE -Value $customer.NAME.TITLE.Trim()
$BuildList | Add-Member -MemberType NoteProperty -Name FIRSTNAME -Value $customer.NAME.FIRST_NAME.Trim()
$BuildList | Add-Member -MemberType NoteProperty -Name LASTNAME -Value $customer.NAME.LAST_NAME.Trim()
$BuildList | Add-Member -MemberType NoteProperty -Name EMAILCONSENT -Value "0"
$BuildList | Add-Member -MemberType NoteProperty -Name EMAILSOFTOPTIN -Value "2"
if ($customer.ATTRIBUTE.NAME -like "*OPT_EMAIL") {
foreach ($value in $customer.ATTRIBUTE.NAME) {
if ($value -match "theCompany-News and offers on theCompany Womenswear_OPT_EMAIL") {
$BuildList.EMAILCONSENT = "1"
}
if ($value -match "Email Soft Opt In_OPT_EMAIL") {
$BuildList.EMAILSOFTOPTIN = $customer.ATTRIBUTE.'#text'
}
}
}
$CustomerListFull += $BuildList
}
$CustomerListFull
which is incorrectly giving me all three Attribute Name values (into field EMAILSOFTOPTIN)
TITLE :
FIRSTNAME : <PERSON>
LASTNAME : <PERSON>
EMAILCONSENT : 1
EMAILSOFTOPTIN : {T, F, T}
I have tried several things to try and access the value, user <PERSON> yesterday showed me nodes which is great but I can't seem to make it work in my forloop, I'm failing miserably.
$BuildList.EMAILSOFTOPTIN = $customer.SelectNodes("//*[local-name()='ATTRIBUTE'][@NAME='Email Soft Opt In_OPT_EMAIL']").InnerText
$BuildList.EMAILSOFTOPTIN = $customer.[ATTRIBUTE].[NAME='Email Soft Opt In_OPT_EMAIL').InnerText
$nodes = $xml.SelectNodes("//*[local-name()='ATTRIBUTE'][@NAME='Email Soft Opt In_OPT_EMAIL']")
$BuildList.EMAILSOFTOPTIN = $nodes.InnerText
Please help to put me out of my misery
| 1906ec785d2f8ae7623f2ece95ca43b64abc4f2edd898a052c37a2d5f21fbb49 | ['927d6856306a4929a97d65ff97ff0dee'] | Just wondering if better if you had a date table driving this and join your transaction table to it then you should be able to use Sum Partition By for each previous 12 months and count where Transaction <> 0... what if you join below to the table.
The other guys on this site will probably know for sure if this would work.
with years as (
select * from
(values(2006),(2007),(2008),(2009),(2010),(2011),(2012),(2013),(2014),(2015),(2016),(2017),(2018),(2019)
) as t (Year_id))
,months as (
select * from
(values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)
) as t (month_id))
select Year_id,month_id,0 as [Transaction_totals]
from years
cross join months
order by 1,2
|
c9c83bb4e7ecf2ba1e964b0e0caebad83ae65d758222e04891f3268a1f8e1fb2 | ['9287f056c0cd42358023d5f5f959e4a3'] | @heynnema i am an freelancer so it has always been my computer... it is just old so i was experimenting with Linux for the first time... now that i want to keep linux on the machine, i was thinking i should wipe the old data on the windows partition before i delete it to expand the linux partition to the full disk | f7659224e9f197f14cedff4598d0f2ae9c8772e3121c0e818b2571112ebcf9f4 | ['9287f056c0cd42358023d5f5f959e4a3'] | I disabled the firewall now (don't need it), now it gives other error: `Connection refused` I think it's because port 21 is closed as you said, I tried `telnet localhost 21` and the output: `telnet: connect to address <IP_ADDRESS>1: Connection refused` how do I force it to open port 21? |
0a0eec9530258e2983192346c057b05a3f1e91f61d018f9691fbdb51a8b7ac85 | ['929488a70f2c42c78220c2645d7b52d0'] | On my my machine the following code prints:
$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.6.3
$ runhaskell Why.hs
[1,1,1]
[2,2,2]
But on FP Complete it produces an error: (Unless I switch to GHC 7.8 Preview, LPaste for cloning http://lpaste.net/108096)
src/Main.hs@4:7-4:13No instance for (Monad ((->) (IO Int)))
arising from a use of `return'
Possible fix:
add an instance declaration for (Monad ((->) (IO Int)))
In the expression: return 3
In an equation for `num': num = return 3
Here's the code. I was trying to make a function that repeats an IO action times an IO Int action.
I noticed that GHC derived a weird type signature for num.
import Control.Monad
-- Notice the weird type signature, for - it seems - no reason
num <IP_ADDRESS> IO Int -> Int
num = return 3
rep <IP_ADDRESS> IO Int -> IO [Int]
rep = num >>= replicateM
rep' <IP_ADDRESS> IO Int -> IO [Int]
rep' = do x <- num
replicateM x
main <IP_ADDRESS> IO ()
main = do print =<< rep (return 1)
print =<< rep' (return 2)
| 5192f3c7dcdf1514d01547ed5183d23078269f9e4d1a7cd12c5adc7fe4a194fa | ['929488a70f2c42c78220c2645d7b52d0'] | I propose something little more generic.
Since the size of the images is not known we can center horizontally the text using the text-align property and then centre it vertically by using an absolutely positioned element with top set to 50%.
Code to add:
a.darken span {
width: 100%;
text-align: center;
top: 50%;
left: 0
position: absolute;
}
http://jsfiddle.net/bk2Sd/5/
|
4267594b451b5236a8bf1506a493b94904ae3e2b19aac60d271b3db281eee332 | ['92a4c94152c9450ba36d87ce8231f57b'] | The approach you chose is the way react-admin has implemented it to get joined data by foreign key and IMHO it is not that much of an overkill because on database level you still need to query the other table.
According to documentation,
there is an extra response property for response format GET_MANY_REFERENCE called total:
GET_MANY_REFERENCE { data: {Record[]}, total: {int} }
The ReferenceManyField field component uses this response format to retrieve data using the current record id as the foreign key (parent id) to the referenced resource.
Digging into react-admin code latest version 2.9.0 I see that ReferenceManyField passes props to it's children and it is up to you how you handle the data (e.g. List, DataGrid) and one of the props is total (count of records) which is by default passed to Pagination component.
You can create your own simple functional component to handle these props if you do not want to use anything else:
import React from 'react';
const UserTotal = props => <div>User count: {props.total}</div>;
export default UserTotal;
And the usage of your reference field:
<ReferenceManyField
label="Users"
reference="users"
target="uuid_organization"
sort={{ field: 'email', order: 'ASC' }}
>
<UserTotal />
</ReferenceManyField>
| 0b7eaa58c565f24cedd38553f0caf8e802b3462c36aa2084c5aa71d2bfdc7f8a | ['92a4c94152c9450ba36d87ce8231f57b'] | If you do not use Webpack then you can just include the .js files into your HTML page - either use CDN or local files (you can get them by entering bellow links and save as..):
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<script src="//<EMAIL_ADDRESS>/Sortable.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.16.0/vuedraggable.min.js"></script>
Quick example:
var vm = new Vue({
el: '#app',
data() {
return {
list: ['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF']
};
}
});
body {
font-family: "Open Sans", sans-serif;
}
.drag-container {
margin: 5px 10px;
display: flex;
}
.drag-item {
border: 1px solid grey;
padding: 2px;
margin: 5px;
cursor: move;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<script src="//<EMAIL_ADDRESS>/Sortable.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.16.0/vuedraggable.min.js"></script>
<div id="app">
<h1>Vue Dragable Test</h1>
<draggable :list="list" class="drag-container">
<div v-for="item in list" class="drag-item">{{ item }}</div>
</draggable>
</div>
|
a728e93738e54c840ee92267f59ee602aa09ba2992cde379e505ef13207d3060 | ['92c8996148f74ed3a39832a9c5b9b075'] | Good morning, i'm doing a database in firebasse that is showed in a datagridview in visual studio in c#, I wanted to know if that is posssible if when I insert data in the firebase right away refreshing it self automaticly being possible to another computer if using the same program be refreshed in the moment of the criation of the data in the firebase.
| 79c02b3e303076332868701a6f0227a35206cc0b39756338c444862998b3a4bf | ['92c8996148f74ed3a39832a9c5b9b075'] | Didn't work :(
I'm using a timer to check second by sencond if something changes in the database but it doesn't make it in time i think.
Here's a piece of the code if it helps:
public Form6()
{
InitializeComponent();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
IFirebaseConfig ifc = new FirebaseConfig()
{
AuthSecret = "#####################################",
BasePath = "########################################"
//the hashtags are just to get censored
};
IFirebaseClient client;
private void Form6_Load(object sender, EventArgs e)
{
try
{
client = new FireSharp.FirebaseClient(ifc);
}
catch
{
MessageBox.Show("Por favor verifique a conexão com a sua Internet.");
}
dt.Columns.Add("Id");
dt.Columns.Add("Username");
dt.Columns.Add("Password");
dataGridView1.DataSource = dt;
textBox6.Select();
var aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 10000;
aTimer.Enabled = true;
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
FirebaseResponse con = client.Get(@"Cnt/cnt");
int Counter = int.Parse(con.ResultAs<string>());
FirebaseResponse con1 = client.Get(@"Cnt1/cnt1");
int check = int.Parse(con1.ResultAs<string>());
if (check == Counter)
{
}
else
{
var set1 = client.Set(@"Cnt1/cnt1", Counter);
Administrador();
}
}
|
13a7df6d267cd9e388d32d870bc432c39b03a214232e9fa3e89e7c25a3ebda18 | ['92d151d5066346d8b71ba72b980361c7'] | I have a script for YouTube which allows me or anyone else to use on a site to upload videos directly to a YouTube account.
The problem is only the video is uploaded with no video information such as title & description I want the person who is uploading the video to have the options of filling in a form which will then result in the title & description on YouTube.
The script can be seen at the bottom. What I want is for a form to be in place which is something like the following:
Video Title: Cat Drives Car
Video By: MrShoez
Video Description: Watch this video of a cat driving a car.
And the title output would be something as "Cat Drives Car by MrShoez"
Along with the description displaying: This video was submitted on DATE HERE by MrShoez. "Watch this video of a cat driving a car."
*
<?php
$youtube_email = "<EMAIL_ADDRESS><PERSON>
Video Description: Watch this video of a cat driving a car.
And the title output would be something as "Cat Drives Car by MrShoez"
Along with the description displaying: This video was submitted on DATE HERE by <PERSON>. "Watch this video of a cat driving a car."
*
<?php
$youtube_email = "email@address.com"; // Change this to your youtube sign in email.
$youtube_password = "password"; // Change this to your youtube sign in password.
$postdata = "Email=".$youtube_email."&Passwd=".$youtube_password."&service=youtube&source=Example";
$curl = curl_init("https://www.google.com/youtube/accounts/ClientLogin");
curl_setopt($curl, CURLOPT_HEADER, "Content-Type:application/x-www-form-urlencoded");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
$response = curl_exec($curl);
curl_close($curl);
list($auth, $youtubeuser) = explode("\n", $response);
list($authlabel, $authvalue) = array_map("trim", explode("=", $auth));
list($youtubeuserlabel, $youtubeuservalue) = array_map("trim", explode("=", $youtubeuser));
$youtube_video_title = "VIDEO TITLE"; // This is the uploading video name.
$youtube_video_description = "VIDEO DESCRIPTION"; // This is the uploading video description.
$youtube_video_category = "CATEGORY"; // This is the uploading video category.
$youtube_video_keywords = "tags, tags, tags, tags"; // This is the uploading video keywords.
$data = '<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
<media:group>
<yt:private/>
<media:title type="plain">'.$youtube_video_title.'</media:title>
<media:description type="plain">'.$youtube_video_description.'</media:description>
<media:category
scheme="http://gdata.youtube.com/schemas/2007/categories.cat">'.$youtube_video_category.'</media:category>
<media:keywords>'.$youtube_video_keywords.'</media:keywords>
</media:group>
</entry>';
$key = "UNIQUEKEY HERE"; // Get your key here: http://code.google.com/apis/youtube/dashboard/.
$headers = array("Authorization: GoogleLogin auth=".$authvalue,
"GData-Version: 2",
"X-GData-Key: key=".$key,
"Content-length: ".strlen($data),
"Content-Type: application/atom+xml; charset=UTF-8");
$curl = curl_init("http://gdata.youtube.com/action/GetUploadToken");
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_REFERER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
$response = simplexml_load_string(curl_exec($curl));
curl_close($curl);
?>
<script type="text/javascript">
function checkForFile() {
if (document.getElementById('file').value) {
return true;
}
document.getElementById('errMsg').style.display = '';
return false;
}
</script>
<?php
$nexturl = "http://website.com/directurl"; // This parameter specifies the URL to which YouTube will redirect the user's browser when the user uploads his video file.
?>
<form action="<?php echo($response->url); ?>?nexturl=<?php echo(urlencode($nexturl)); ?>" method="post" enctype="multipart/form-data" onsubmit="return checkForFile();">
<input id="file" type="file" name="file"/>
<div id="errMsg" style="display:none;color:red">
You need to specify a file.
</div>
<input type="hidden" name="token" value="<?php echo($response->token); ?>"/>
<input type="submit" value="go" />
</form>
</php>
*
| f8e916957358162db659293967c1f5d537bec9ff1c57ce8ef46fc8faac670de8 | ['92d151d5066346d8b71ba72b980361c7'] | I used st link utility which is a windows program provided by st.
It allowed me to erase and reflash the mcu using SWD interface.
The reason behind my problem was I ticked the Set all free pins as analog to optimize power consumption before generating my project files with CubeMX. It actually broke the boot config as BOOT0 pin was set to analog.
TLDR: don't tick Set all free pins as analog in CubeMX
|
fed13b958c9e046ba6a0e1715edd56d27e318ad791da5fcfbb70a6c284c47606 | ['92f81234f58947e79aecbf8dfb165ae4'] | There are a few things that can be changed in your example:
The fpx, fpy properties belong to source1, not to source.
Math.fps should be Math.abs.
You have a typo in the field names when retrieving x1 and y1.
The second loop in CustomJS callback wouldn't quite work if the number of zeros changes.
One way to rewrite the callback is as follows:
callback_single = CustomJS(args=dict(source=source, source1=source1), code="""
const mu = cb_obj.value
const { x } = source.data;
const y = x.map( val => mu * Math.sin(val) - Math.sin(2*val));
source.data = { x, y };
const fpx = x.filter((val, ind) => Math.abs(y[ind]) < 0.05);
const fpy = fpx.map(() => 0);
source1.data = { fpx, fpy };
""")
Also, there is a way to use more idiomatic numpy in init_fp:
def init_fp(x, y):
fp_x = x[np.abs(y) < 0.05]
fp_y = np.zeros_like(fp_x)
return fp_x, fp_y
Here is the complete code, I left the math of zeros as is and also changed from output_notebook to output_file:
from bokeh.io import show, output_file
from bokeh.layouts import column, widgetbox
from bokeh.models import ColumnDataSource, CustomJS, Slider, Title
from bokeh.plotting import figure
import numpy as np
output_file('zeros.html')
mu = 0
x = np.linspace(-2*np.pi, 2*np.pi, 2000)
y = mu*np.sin(x)-np.sin(2*x)
def init_fp(x, y):
fp_x = x[np.abs(y) < 0.05]
fp_y = np.zeros_like(fp_x)
return fp_x, fp_y
source = ColumnDataSource(data={
'x' : x,
'y' : y
})
fpx, fpy = init_fp(x, y)
source1 = ColumnDataSource(data={
'fpx' : fpx,
'fpy' : fpy
})
callback_single = CustomJS(args=dict(source=source, source1=source1), code="""
const mu = cb_obj.value;
const { x } = source.data;
const y = x.map( val => mu * Math.sin(val) - Math.sin(2*val));
source.data = { x, y };
const fpx = x.filter((val, ind) => Math.abs(y[ind]) < 0.05);
const fpy = fpx.map(() => 0);
source1.data = { fpx, fpy };
""")
mu = Slider(start=-5, end=5, value=0, step=0.01, title="mu", callback=callback_single)
p = figure(plot_width=1000, plot_height=500)
p.line('x', 'y', source=source)
p.circle('fpx', 'fpy', source=source1)
p.xgrid.grid_line_color=None
p.ygrid.grid_line_alpha=0.8
p.xaxis.axis_label = 'Theta'
p.yaxis.axis_label = 'd Theta/dt'
t = Title()
t.text = 'Interactive Phase Plane Plot'
layout = column(p, widgetbox(mu))
p.title = t
show(layout)
| a7752e46800adb6ccb51dff78e92cc14cb2f07010152aa569e01adb6ec36840d | ['92f81234f58947e79aecbf8dfb165ae4'] | I used <PERSON>'s answer to write this decorator
import doctest
import copy
import functools
def test(func):
globs = copy.copy(globals())
globs.update({func.__name__:func})
doctest.run_docstring_examples(func, globs, verbose=True, name=func.__name__)
return func
See a gist with a doctest: https://gist.github.com/2torus/f78b7cef5770927a92e3ca652f38ff89
|
c7b8df6f9d54f00fb1758e2e0140cdafd13e6c2ae9c7ca7233d3ee12a8c8b67f | ['92f844a9de634401a48be9df41a7bac2'] | I've got a DataGrid that Auto Generates it's columns.
In Code i implement The AutoGeneratingColumn Event, to set a certain template for my Translation Datatype:
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if(e.PropertyType == typeof(Translation)){
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.CellTemplate = (DataTemplate)Resources["LanguageTemplate"];
e.Column = templateColumn;
}
}
DataTemplate:
<DataTemplate x:Key="LanguageTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="20"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name.ActualTranslation}" HorizontalAlignment="Stretch" Grid.Column="0"></TextBlock>
<Image Source="{lex:LocImage en}" Height="15" HorizontalAlignment="Right" Grid.Column="1" Visibility="{Binding Name.HasCurrentLanguage, Converter={StaticResource boolToVis}, ConverterParameter=true}" ></Image>
</Grid>
</DataTemplate>
Now a problem occured: The TextBlock is bound to Name Property. That works fine if the object to be displayed has a Name Property. But if i have Translation properties that are not named "Name" obviously no data is shown. How would i bind correctly to cover all Translation Items.
| d8834bc0262069c34c9f1bcd5059b9055675af4b457b18cd9b0bd356d279be83 | ['92f844a9de634401a48be9df41a7bac2'] | In a (Inner)Join like in the first example only the rows that match a row in the other table are selected.
In the Left Join all rows from Table A are selected. If there are no rows in the second table that fit the join the columns for the second table are filled with NULL values. The Objects that are created are having a Integer Property. Integer Properties don't except NULL Values.
You either have to change the Integer Property to a nullable datatype or make the Integer Property nullable.
|
a57193e073b0e7bff0be8163d5b52603000318ca30cb3c5f78019ba179aa6075 | ['9302709494b74235bac9c56fdd07421d'] | I am trying to see which health indicators get auto configured in spring boot actuator. i'm using spring boot 2.2.6, when I run my application locally and I navigate to /actuator/health I see "Status":"up". when I deploy my application on a openshift cluster however the status always shows down so i'm guessing one of the auto configured health indicators are failing. I use a custom JWT security implementation and it would be impossible to configure the Openshift readiness and liveness probes to use my security implementation. I tried all suggestions I could find on Stackoverflow to set the actuator health endpoint to show all details including setting management.endpoint.show-details to always, management.endpoints.sensitive to "*" or false, management.security.enabled to false etc etc. Nothing seems to work and i'm running out of ideas... i'm thinking that I manually need to start disabling all health checks and then re-enable them one by one to debug this? Any help/suggestions would be much appreciated, my latest management section of my application config file is below...
my config:
management:
security:
enabled: false
#defaults:
#enabled: false
#consul:
#enabled: false
endpoint:
health:
show-details: always
show-components: always
solr:
enabled: false
endpoints:
health:
sensitive: "*"
web:
exposure:
include: "*"
| 44a6d60312915dc2583dd4094e9bd09772314f33c3d74f7102cd20c1472b3bfd | ['9302709494b74235bac9c56fdd07421d'] | I have a search suggestion component that is displayed under a TextField. whenever text is entered into the TextField the search suggestion component displays a list of possible matches based on the current entered text... I have more content under the TextField that gets pushed to the bottom whenever the Search suggestion gets populated with results. Is there any way to overlay the search suggestions over the content underneath it instead of pushing the content down? in HTML/css I would apply the position absolute and z-index css properties to the search suggestion component but this doesn't seem to be the case in Nativescript. I see that Nativescript does support the z-index css property but just applying that doesn't seem to do anything. It doesn't look like Nativescript supports the position property... Any idea how I can make this work/what i'm missing?
|
4f270bf1925ce995645c61f55c8dd61a6b45ac943116db2efccff3c2a84d8aa3 | ['932243cc32524017ab9ed2fb053e4173'] | Ok, I have a solution.
All I wanted is to group by _id but to return the result documents with their _id field (which is been overwritten when using $group operator).
What I did is like <PERSON> said, I've added comment_id : { "$first" : "$_id" } but then I wanted not to return the comment_id field (because it doesn't fit my model) so I've created a $project which put the comment_id in the regular _id field.
This is basically how it looks:
Comment.aggregate(
{
$match: {
"sharedToUsers": [], "repliedToUsers": []
}
},
{
$group: {
comment_id: { $last: "$_id" },
_id: "$user.id",
content: { $last: "$content" },
urlId: { $last: "$urlId" },
user: { $last: "$user" }
}
},
{
$project: {
_id: "$comment_id",
content: "$content",
urlId: "$urlId",
user: "$user"
}
},
{ $skip: parsedFromIndex },
{ $limit: (parsedNumOfComments - parsedFromIndex) },
function (err, result) {
console.log(result);
if (!err) {
Comment.populate(result, { path: "urlId"}, function(err, comments) {
if (!err) {
res.send(comments);
} else {
res.status(500).send({err: err});
}
});
} else {
res.status(500).send({err: err});
}
});
thanks <PERSON>!
| 1e9fedd299f0f6c019f22208e3e9a7aef626b23ac6e7dc1ffef3c7338e8c6b92 | ['932243cc32524017ab9ed2fb053e4173'] | I have this kind of 'comment' model:
{ _id: <comment-id>,
user: {
id: { type: Schema.ObjectId, ref: 'User', required: true },
name: String
},
sharedToUsers: [{ type: Schema.ObjectId, ref: 'User' }],
repliedToUsers: [{ type: Schema.ObjectId, ref: 'User' }],
}
And I want to query for all comments which pass the following conditions:
sharedToUsers array is empty
repliedToUsers array is empty
But also, I want the result to contain only 1 comment (the latest comment) per user by the user id.
I've tried to create this aggregate (Node.js, mongoose):
Comment.aggregate(
{ $match: { "sharedToUsers": [], "repliedToUsers": [] } },
{
$group: {
_id: "$user.id",
user: { $first: "$user" },
}
},
function (err, result) {
console.log(result);
if (!err) {
res.send(result);
} else {
res.status(500).send({err: err});
}
});
It is actually working, but the serious problem is that the results comments _id field is been overwritten by the nested user _id.
How can I keep the aggregate working but not to overwrite the original comment _id field?
Thanks
|
f926fbea107f5c30e69877f7eb938736f7a5f3bdea5865e97b74c765240c6e00 | ['9331a30e3c2448dca5e2534e3e765011'] | i tried, and is not working. The DNS was set correctly, but maybe there is some kind of conflict, since the new server is the old backup server, so we have switched the domains in this order: the old backup.domain.com has now become site.domain.com, and the old site.domain.com is now backup2.domain.com | 32148727a7d9a7ba6f03544b833abaf8ad8e155da85399c4e4ed0e1b6f3fa284 | ['9331a30e3c2448dca5e2534e3e765011'] | I had a very similar issue with an iMac mid 2017. During an update to High Sierra it just went into a reboot cycle, I'm fortunate enough to have access to another Mac so I target disked the iMac todo a backup just incase. I downloaded the Latest macOS via the App Store and created a bootable USB and then booted the iMac from that USB, started the Install wizard and just installed macOS 10.13.3 straight over the damaged OS and It worked, zero data loss and all apps work as they did before the failure. Best of Luck to anyone who encounters this.
|
581ea16cf57e6aca910f482e9b8944a5991ee04c38731668d45280839c251310 | ['9340d36a4fcb424cbabbdd178fea6995'] | The line txtTest.text = (1234.5678).toString() is just telling the VM that it should use the standard number-to-string conversion proccess, so it will put a dot as a decimal separator and, if you use a double with more decimal places, it will even use scientific notation. You should, instead, have a look at this page from Android Developers, where there are specific methods to work with number formatting: https://developer.android.com/reference/java/text/DecimalFormat
| a12e37572dc5dbbcae7e3e004553ae3dba8bab2d2de6136b62f5595ef6f9b9fe | ['9340d36a4fcb424cbabbdd178fea6995'] | I'm not sure if you want to use the found instantiantions for something or if you just need to count them, but, if this is the case, then you may simply use the Find in Path tool in IntelliJ/Android Studio with the Regex option checked and search for this: (\(|\[|\{|( ))([A-Z][a-z0-9]+)+\(, which matches CamelCased strings after (, [, { or [space] and are followed by a (, just like we call constructors in Kotlin if we are using a standard formatting design.
|
a59bc3828729f828b6687767f2ebeefb6c69d8e7adb52d1436b5cc0316a3bbd5 | ['934193be66a640e6becb344213295ebc'] | im getting this two errors:
Notice: Trying to get property 'users' of non-object in /Applications/MAMP/htdocs/ig_stats/jsontest.php on line 5
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/ig_stats/jsontest.php on line 5
Im trying:
$json = json_decode(file_get_contents('https://www.instagram.com/web/search/topsearch/?query=lol'));
foreach($json->users as $item)
{
if($item->user->username == "lol")
{
echo $item->full_name;
}
}
All i want is to get the data in 'full_name' from the 'user' 'lol'.
But i dont know how i can search for it :/
Can someone give me a hint or a solution?
| ea843500c7aaa3d2daa2ecdc1beddd156b58043b8cf764263d4836ccf7dc31ca | ['934193be66a640e6becb344213295ebc'] | im currently trying to login to my account at ds-exchange (https://app.ds-exchange.co.uk/#/login/signin) via Python (Dont ask why, im just testing what i can do with Paython currently since im learning it :P )
I've checked a bit how their login works with Fiddler:
They do an empty post @ https://api.ds-exchange.co.uk/v1/get/ip/
They do post device_id, app_type, platform, app_version & identifier which they've got from step 1. @ https://api.ds-exchange.co.uk/v1/device/register/
Now they post email, password(in sha256) and access_token @ https://api.ds-exchange.co.uk/v1/login/
I've rewrite it simply in Python:
import re
import json
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
#disable ssl warning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
payload = {}
content = requests.post('https://api.ds-exchange.co.uk/v1/get/ip/', verify=False, params=payload)
print(content.text)
payload = {'device_id': '123123123123123', 'app_type': 'admin', 'platform': 'web', 'app_version': '2.0.1', 'identifier': '127.0.0.1'}
content = requests.post('https://api.ds-exchange.co.uk/v1/device/register/', verify=False, params=payload)
print(content.text)
answer = json.loads(content.text)
print(answer['data']['access_token'])
accesstoken = answer['data']['access_token']
payload = {'email': '<EMAIL_ADDRESS>', 'password': 'dolemites', 'access_token': accesstoken}
content = requests.post('https://api.ds-exchange.co.uk/v1/login/', verify=False, params=payload)
print(content.text)
That are the answers i got from python script:
Step 1: {"ts":1534762909,"success":true,"error":false,"data":{"ip_address":"::1"}}
Step 2: {"ts":1534762911,"success":true,"error":false,"data":{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZHMiOiIyZTAxZmI0MDUyZTEyZjdmMzU2OTliZWVmODU3Zjk2MTY5ODBmMDA0MDMwOTFmM2M3OTk3NzdhYzRjZDM0YTEyIiwiaWF0IjoxNTM0NzYyOTExLCJleHAiOjE1MzQ4NDkzMTEsImF1ZCI6ImNyeXB0b2JhbmsuY29tIiwiaXNzIjoiY3J5cHRvYmFuay5jb20ifQ.aYAcdRmYdRPxYtylh17gYJKjXYKiRhWlWRg-JnmFYBw"}}
Step 3: {"ts":1534762912,"success":false,"error":true,"error_msg":"Access Denied. Token not found","logout":true}
The problem is that im getting a completly different answer in Fiddler in step 3, im getting there this: "error_msg": "<EMAIL_ADDRESS><IP_ADDRESS>'}
content = requests.post('https://api.ds-exchange.co.uk/v1/device/register/', verify=False, params=payload)
print(content.text)
answer = json.loads(content.text)
print(answer['data']['access_token'])
accesstoken = answer['data']['access_token']
payload = {'email': 'dolemites@test.de', 'password': 'dolemites', 'access_token': accesstoken}
content = requests.post('https://api.ds-exchange.co.uk/v1/login/', verify=False, params=payload)
print(content.text)
That are the answers i got from python script:
Step 1: {"ts":1534762909,"success":true,"error":false,"data":{"ip_address":"<IP_ADDRESS><PHONE_NUMBER>,"success":true,"error":false,"data":{"ip_address":"::1"}}
Step 2: {"ts":<PHONE_NUMBER>,"success":true,"error":false,"data":{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZHMiOiIyZTAxZmI0MDUyZTEyZjdmMzU2OTliZWVmODU3Zjk2MTY5ODBmMDA0MDMwOTFmM2M3OTk3NzdhYzRjZDM0YTEyIiwiaWF0IjoxNTM0NzYyOTExLCJleHAiOjE1MzQ4NDkzMTEsImF1ZCI6ImNyeXB0b2JhbmsuY29tIiwiaXNzIjoiY3J5cHRvYmFuay5jb20ifQ.aYAcdRmYdRPxYtylh17gYJKjXYKiRhWlWRg-JnmFYBw"}}
Step 3: {"ts":<PHONE_NUMBER>,"success":false,"error":true,"error_msg":"Access Denied. Token not found","logout":true}
The problem is that im getting a completly different answer in Fiddler in step 3, im getting there this: "error_msg": "dolemites@test.de is not found"
What im doing wrong? :(
|
997b15e579c3da642940e0af6d70625c8c64a14caa666f1a87f7fda7a42cdc2a | ['934321d16f1140d7922779b0e569c81a'] | I assume you want the equivalent of the phrase "victim of bad luck" when you want to say "____ of good luck", to convey the idea that the person in question has done nothing to warrant the good or bad circumstances that have arisen. I would use the phrase "beneficiary of good luck".
Used in this context, 'beneficiary' has the especial connotation of being a passive recipient of a benefit. So while you could say (as in the example in one of the other answers) "If a person lights a candle… he will be the recipient of good luck", it would be quite odd to say the same sentence with 'beneficiary', since the person has purportedly done something to bring the good luck about.
The first example that popped into my mind is this eulogy by <PERSON>. The relevant context is at 0:18 – 0:53; she uses the phrase "I am the beneficiary of free tertiary education" at 0:46 (and similar phrases several more times), which I think very nicely conveys the connotation of 'beneficiary' used in this way.
| 76b4ef108d50d16b6a81aeb8a1422442d646bde27a7857864aac11790da5e45b | ['934321d16f1140d7922779b0e569c81a'] | The other answers correctly highlight, I think, the fact that time is unforgiving in that time passed is gone forever. But why the 'minute' instead of some other measure of time? Here are two interpretations that seem plausible:
(1) The minute is unforgiving in a way that the hour or the day is not because of how fast it passes – a moment of distraction and a minute is gone. Hence the exhortation to occupy every second of every minute with whatever task is at hand ('distance run'), because even if 60 seconds doesn't seem like much time when trying to complete most tasks (including running), you'd take much longer to accomplish anything if you're not focused on the task for all 60 seconds in each minute.
(2) The minute might be unforgiving in another way if the task at hand is arduous or painful – 60 seconds is a long time to endure if you're having a terrible time, but at the same time a minute is such a short period of time in the context of most arduous or painful tasks (imagine running a marathon or doing a repetitive menial task). But the only way to get closer to your goal is to fill all 60 seconds of every minute with your fullest effort.
Of course, in both cases this image resonates more clearly with some things in life than others.
|
6084a76931cbd770e314a94c66af48663d1bf076eaa5301315201488ed683683 | ['93534b5fddcf43498f21a7310234996a'] | I would like to add a logo over my google map in my android app, but i dont want it to interfere with map dragging. If the dragging starts where the logo is, the dragging doesnt take place.
Is there a way to add the image in such manner that touching it i actually touch the map?
This is the way i am adding the ImageView:
final ImageView tv = new ImageView(AppContext);
tv.setTag(tt);
tv.setId(ctlid);
dh.addView(tv, params);
I am not setting any touch listeners, but the image still interferes between the touch and the google-map.
| e84d616d54add381711d30915f5157f91de58ca24b26a49b4525d821728b316c | ['93534b5fddcf43498f21a7310234996a'] | I am creating a relativelayout programmatically in onCreate like this:
RelativeLayout rl = new RelativeLayout();
//I add all the views here.
RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
rp.addRule(RelativeLayout.CENTER_IN_PARENT);
setContentView(rl, rp);
And i am currently switching from one to another with:
RelativeLayout rn = (RelativeLayout) Framework.layouts(rlo);
if (rn!=null) {setContentView(rn);}
Works fine and everything, now, i am trying to add a crossfade effect between the two layouts.
Is there a way to do it programmatically without xml files and without the android.R.anim animations?
For every single question i have made i end up getting answers like better solutions or something, but I have good reasons for this, thanks.
|
8cdbf77594f335d4b80b1eeae6d2061a3c2f08c24a8cfd2694c73c48752591ab | ['9358f080b4514c6ab73c2ebd7f4befd7'] | I'd use a context. Because the Game component is where the data is going to be arranged and populated then to post, right?
I don't know if it is the best option, but with a context you could write, and access data from every level of your app without having to pass it through props.
I'd create all the logic of the api on the game component (or the most upper level component), and make it the provider of the context. So every child component can access to the functions.
Update us!
| 2e1264f1bf493cbc3682cd95d40ec3d58de685b823503dd20f1ea8bbdbfa4864 | ['9358f080b4514c6ab73c2ebd7f4befd7'] | I need to get an object inside a variable inside a node which is a javascript node.
(Using scrapy 1.8.0 didn't update yet hehe)
Maybe I don't explain myself clearly but as soon you see it... you will understand.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script id='myscript'>
oneVariable = {...}
theVariable = {"Data": "blahblah", "More-Data": {...}}
</script>
</head>
<body>
</body>
</html>
Ok I got the whole node with his information manually using scrapy shell and then the selector
response.xpath('//*[@id="myscript"]').get()
Can I get the "theVariable" I want just with XPATH selectors or functions (like get(), getAll() etc)?
Thanks in advance!
|
64af61fc694877f8e6c6f23428060d586a2959ca5d16512f141440d378f6c7ed | ['9359c30b10de49358782a2257d479fc5'] | I believe you want to check different types of input fields, hence want to use change and keyup.
I tried something based on your code, but this following solution will only work, if you want to validate text type input fields. For select or other input types you have to put some more checks inside the loop or have to some other way to validate.
$('.inputfields').each(function() {
$(this).bind('change keyup', function() {
var ope = $(this).attr('name');
if ($(this).val() == '') {
console.log(ope+'is empty');
} else {
console.log(ope+ ' : ' + $(this).val());
}
});
});
Hope this will lead you to find your desired solution.
| 46370904dee7191163e3c009ba99abb06487466baec2fe2954fd6c1e800b53b5 | ['9359c30b10de49358782a2257d479fc5'] | I'm guessing you're manually managing active/inactive projects. It would be better to a new field in the table to manage the status of the projects (or have some other way to differentiate the project status). You can group projects based on their status and then display accordingly.
This sample might help
http://www.trirand.net/demo/php/jqpivotgrid/
|
83f50708ab319695f36c27d34843f692e33f94dceb6e385f9ea6aa51a6897a84 | ['935a7a733b5c4f0a8aa66756e9b98a77'] | im coding a registration for an old game, this games uses PASSWORD() for encryption.
Is there a way to use that function in Laravel Eloquent?
current form:
public function registerPost(Request $request)
{
$request->validate([
'login' => 'required|min:4|unique:account',
'email' => 'required|email|unique:account',
'password' => 'required|min:8',
'repeat_password' => 'required|same:password',
], [], [
'login' => 'Username',
'password' => 'Password',
'email' => 'E-Mail',
'repeat_password' => 'Repeat password'
]);
$data = $request->all();
if (Account<IP_ADDRESS>create($data)) {
return Redirect<IP_ADDRESS>to("/registration")->withErrors(['success' => 'Account created']);
}
return Redirect<IP_ADDRESS>to("/registration")->withErrors(['message' => 'Account creation failed']);
}
| 4c58870d26a41179385dee5e0554493d112416a9dd70af2c6113074454ccf86a | ['935a7a733b5c4f0a8aa66756e9b98a77'] | I created a VueJs application which is embedded in an existing site.
the existing site has its own set of javascript (bootstrap, jquery etc.)
The issue is now that my runtime chunk calls the existing scripts from the site which adds for example multiple event listeners on a button instead of one.
vue.config.js
module.exports = {
publicPath: '/b2b_platform/',
runtimeCompiler: true,
configureWebpack: {
optimization: {
runtimeChunk: { name: 'runtime' },
splitChunks: {
cacheGroups: {
'runtime-vendor': {
chunks: 'all',
name: 'vendors-node',
test: path.join(__dirname, 'node_modules')
}
},
minSize: 0
}
},
...
the runtime script which causes the issue
(function (e) {
function r(r) {
for (var n, l, i = r[0], a = r[1], f = r[2], c = 0, s = []; c < i.length; c++) l = i[c], Object.prototype.hasOwnProperty.call(o, l) && o[l] && s.push(o[l][0]), o[l] = 0;
for (n in a) Object.prototype.hasOwnProperty.call(a, n) && (e[n] = a[n]);
p && p(r);
while (s.length) s.shift()();
return u.push.apply(u, f || []), t()
}
function t() {
for (var e, r = 0; r < u.length; r++) {
for (var t = u[r], n = !0, i = 1; i < t.length; i++) {
var a = t[i];
0 !== o[a] && (n = !1)
}
n && (u.splice(r--, 1), e = l(l.s = t[0]))
}
return e
}
var n = {}, o = {runtime: 0}, u = [];
function l(r) {
if (n[r]) return n[r].exports;
var t = n[r] = {i: r, l: !1, exports: {}};
return e[r].call(t.exports, t, t.exports, l), t.l = !0, t.exports
}
l.m = e, l.c = n, l.d = function (e, r, t) {
l.o(e, r) || Object.defineProperty(e, r, {enumerable: !0, get: t})
}, l.r = function (e) {
"undefined" !== typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, {value: "Module"}), Object.defineProperty(e, "__esModule", {value: !0})
}, l.t = function (e, r) {
if (1 & r && (e = l(e)), 8 & r) return e;
if (4 & r && "object" === typeof e && e && e.__esModule) return e;
var t = Object.create(null);
if (l.r(t), Object.defineProperty(t, "default", {
enumerable: !0,
value: e
}), 2 & r && "string" != typeof e) for (var n in e) l.d(t, n, function (r) {
return e[r]
}.bind(null, n));
return t
}, l.n = function (e) {
var r = e && e.__esModule ? function () {
return e["default"]
} : function () {
return e
};
return l.d(r, "a", r), r
}, l.o = function (e, r) {
return Object.prototype.hasOwnProperty.call(e, r)
}, l.p = "/b2b_platform/";
var i = this["webpackJsonp"] = this["webpackJsonp"] || [], a = i.push.bind(i);
i.push = r, i = i.slice();
for (var f = 0; f < i.length; f++) r(i[f]);
var p = a;
t()
})([]);
//# sourceMappingURL=runtime.js.map
everything works after removing function t() but I have no clue how to fix that
|
2640554e38ba767b1c149386f86ef0b032ce57a76d60a9c75d1ea9114292a1bd | ['93701c58042140f18e2069e632806602'] | The problem is in the where statement:
a.EH_PP_TOSRT_TeacherObservationStatusIDEH is not equal new Guid("A717732D-68FA-47FE-A354-C2CB589F29FA")
try Convert.ToString(a.EH_PP_TOSRT_TeacherObservationStatusIDEH).ToUpper() = "A717732D-68FA-47FE-A354-C2CB589F29FA"
Note: Guid is struct, so comparing struct in C# is a pain, equals always return false if even your objects have the same value.
| bef8305f16c1fa98e3e7d47e06d8d515b5d9c31c370a58678a3345d329830c70 | ['93701c58042140f18e2069e632806602'] | I noticed you're using anonymous authentication to login to your AD, I think you want to use username and password, then see if the user exists. Try the code below:
public bool IsAuthenticated(string username, string pwd)
{
string strLDAPServerAndPort = "ldap.domain.com:389";
string strLDAPContainer = "CN=Users,DC=domain,DC=com";
string strLDAPPath = "LDAP://" + strLDAPServerAndPort + "/" + strLDAPContainer;
DirectoryEntry objDirEntry = new DirectoryEntry(strLDAPPath, username, pwd);
try
{
//Bind to the native AdsObject to force authentication.
object obj = objDirEntry.NativeObject;
DirectorySearcher search = new DirectorySearcher(objDirEntry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
}
|
7245b5add928653091182021bf9a6017aaa2840a63e9a7ce763192ea2488c88c | ['937c619620f8493dac711b7695f951ae'] | ES1 compatible :
const a = [
{label: 'All', value: 'All'},
{label: 'All', value: 'All'},
{label: '<PERSON>', value: '<PERSON>'},
{label: '<PERSON>', value: '<PERSON>'},
{label: '<PERSON>', value: '<PERSON>'}
]
for (let i = 0; i < a.length; ++i)
for (let j = 0; j < a.length; ++j)
if (i !== j && a[i].label === a[j].label && a[i].value === a[j].value)
a.splice(j, 1);
console.log(a);
| 15f37fbbe30d699f94e9be6cedc6119adf6e214b826bb4a18321d4ec33f21e3c | ['937c619620f8493dac711b7695f951ae'] |
const keywords = ["anacell", "cetracular", "betacellular"];
const reviews = [
"Anacell provides the best services in the city",
"betacellular has awesome services",
"Best services provided by anacell, everyone should use anacell",
];
let occurences = [];
for (const kw of keywords)
for (const rw of reviews) {
const lower = rw.toLowerCase();
const lower2 = kw.toLowerCase();
if (occurences.indexOf(lower2) < 0 && lower.indexOf(lower2) >= 0)
occurences.push(kw);
}
console.log(occurences);
|
1c2ed87471cea9862dea827041eaffd74a5649d6ffc9d671d42e70daaaa7d452 | ['93873ebdad8b489cb53419b595b1c7fc'] | Answering my question for posterity, in case anyone ever does something similar, which is highly unlikely!
In my tests, I had only been connecting to the box with vagrant ssh, and was typing in my original terminal window. I changed my Vagrant file to include a gui, with config.vm.provider "virtualbox" { |v| v.gui = true }, and vagrant launched a CLI window with the guest. The typing in that terminal worked, and the debug was output to the original terminal.
Unfortunately I don't have time to investigate exactly why the keystrokes on the host box weren't showing up in the guest ... probably something obvious I'm missing. If anyone has a good idea, please post as I'm interested.
| 1307af77d45908062ab0f98fe5b37520b4e9abf6f15cc69cfffaaa9db138e6e6 | ['93873ebdad8b489cb53419b595b1c7fc'] | @PM2Ring Cheers. So I understand, "Eg if there are 12 sectors, each sector occupies 30°, so for the 1st sector θ=15°, for the second, θ=45°" Is this the angle of the midpoint for each segment? Yes, I'm working in radians in my program. However, I have a piece of code that converts from degrees to radians. |
9d11ac9742c2f229c87e09f30de38cdb4343f945d058e15672b3bba162cdc1ca | ['9390e66acacc444392019b4fa3fc5564'] | I've tried downloading and deployed the Proximity Sample Code link. But i'm unable to do anything with regards to NFC.
Then i did a search on YouTube and found this. Is this even NFC? From what i know, NFC stands for Near Field Communication and typically, they can only receive/transmit data when the tag/device is of close proximity (1-2 cm away).
I'm using an SCL3711 hardware. I've tried using running the Sample Code provided by the hardware maker - IDENTIVE. It works alright if i'm creating a WPF project. Some classes don't exist on WindowsRT (In particular, System.Windows.Form.Message).
All i need is an application that can develop a Windows 8 (Windows Store) application that is able to read and write data to an NFC tag. Any help is appreciated.
| 188600a272ab8c061ac30614d2b10e6f9eac45df867a67dd3f010f7937ccf922 | ['9390e66acacc444392019b4fa3fc5564'] | Normally, just name the Grid/Stack. Like for my case, i would name my Grid as 'grid'. Then to add it into the form, i would do this.
WebBrowser wb = new WebBrowser();
grid.Children.Add(wb);
Subsequently, if you need to shift it left or right, you would need to mess with the margin.
Thickness t = new Thickness { Top = 5, Left = 5, Right = 5, Bottom = 5 };
wb.Margin = t;
Hope this helps.
|
e4197204bfd2d8f5fb58ff374e03c56dc203323c9710d7526e68ec8381bc044a | ['93d058b84f1b4f37b11535f37b270d42'] | This error occurs when you try to parse invalid JSON.
Due to the default response type for angular is JSON and the default response of code 200 is 'OK'. You have to adapt one of them.
You can change the response type to text like this:
this.http.post<User>(url, pUser, {responseType: 'text'});
Or you return a JSON object:
res.status(200).send({ status: 'OK'});
| e065dc6aa607e90843045d08ab27b90e65bcf51565686dc8ffa10911da834762 | ['93d058b84f1b4f37b11535f37b270d42'] | You could simply add custom styles to your drag list.
<th mat-header-cell class="drop-list
css
.drop-list{
width: 100%;
border: solid 1px #ccc;
min-height: 60px;
display: block;
background: white;
border-radius: 4px;
overflow: hidden;
}
This are just examples styles you have to adjust them to fit your needs.
For further examples see here
Also cdkDropList and cdkDrag should not be on the same element.
Set cdkDropList to your <th> and cdkDrag to you <td>
|
266ad2ab4694c1fd38c3dd47bcdc272248d04246a715e3d6d62c0038ff29e791 | ['93d05dd4b8aa406799b8b295412766e8'] | I have a Samsung Galaxy 8.Every 5 minutes or so I hear my phone buzz then I hear a gong sound. This gong sound is driving crazy.
Here is what i tried:
1: restarted my phone
2: killed all applictions
3: Ran a good antivirus
Also every time this song comes, if im watching a video on YouTube It causes to pause.
Any ideas?
| 2265c075a84d30084229e3fb3b35ecc81aa5c4e415ce3a63e864fd2843be4285 | ['93d05dd4b8aa406799b8b295412766e8'] | Я новичок в rails. Исходя из опыта с django лень было писать админку руками и я стал использовать active admin.Столкнулся с проблемой загрузки изображений.
1) Не знаю как указать путь загрузки
2) не знаю как загрузить файл.
Заранее спасибо!
вот мой код:
ActiveAdmin.register Imgpost do
permit_params :title, :image
index do
column :title
column :image
actions
end
filter :title
form(:html => { :multipart => true }) do |f|
f.inputs "Create new image post", :multipart => true do
f.input :title
f.input :image, :as => :file
end
f.actions
end
end`
|
f50779c4edb81e58c2bd45302c7266f659f98f2987e153c9ce22d173a9b4c43f | ['93d98ea9ba9b4f728ff1f94b76e4c8d9'] | (I'm sorry if you see some english problem, I'm french !)
I have a problem with a method in a Java Projet using kafka.
I've got a database of prices and i want to send to kafka a message with all the information of a price when I delete a price.
In my Endpoint.java I've a methode for deleteById(idPrix) :
@DeleteMapping
@RequestMapping(value ="/delete{idPrix}")
public Mono<Void> deleteById (@RequestParam(required = true, name = "idPrix") Long idPrix){
return priceservice.deleteById(idPrix).map( data -> {
ProducerRecord<String, Price> producerRecord = new ProducerRecord<>(TOPIC, idPrix.toString(), data );
kafkaTemplate.send(producerRecord);
return null;
});
}
I got this message : cannot infer type arguments for ProducerRecord<>
I've tried so much different things to make it work but no success. If someone see what's the problem it will be great.
| 3ed57e8e1a3de32be4955126d6ec1f72aa20c13390f7e71bd2cd5f21d17eef38 | ['93d98ea9ba9b4f728ff1f94b76e4c8d9'] | I got a problem with a link I've tried to make. I want to have a page with an article, and a link to the author page of it. Iv's try 100 differents version but i don't know how to do...
Here is my code :
<a <% link_to " Par : #{@article.author.pseudo}", user_path(User.where(user_id: @author_id) %></a>
or with this path : user_path(Article.find(params[:id]).author_id)
If you know how I can resolve that... Thanks !
|
78ffafe4a9c216e577c006facc8e5b6116e4632f81159d8c9e7f0f27322681bb | ['93dcd5161a2e414cb9f2fca21dc9e77b'] | I downloaded the server site and set to run on localhost. But he is not making the call of the files correctly. First, he calls "http://localhost" and then the folder path, with backslash.
There is a rule set to call all the files:
<?php
define("MY_BASE_DIR", 'C:');
define("SITE_PATH", __DIR__ . '/');
define("SITE_VIRTUAL_DIR", str_replace($_SERVER["DOCUMENT_ROOT"], "", SITE_PATH));
define("ENGINE_PATH", SITE_PATH.'includes/fw/'); // caminho pro FW
define("CMS_ENGINE_PATH", SITE_PATH.'includes/cms/cms.php');
?>
I tried to change this rule, but without success /:
This backslash setting is a passage in the code files that have changed or whether it is my local server configuration (I'm using WampServer)?
This is the file that gives way to the files:
public function Setup()
{
parent<IP_ADDRESS>Setup();
if (\Browser<IP_ADDRESS>Obsolet())
{
$this->context->UpdateYourBrowser();
}
if(!defined("ADMIN_DIR")){
define("ADMIN_DIR", dirname($_SERVER["SCRIPT_NAME"]) . "/");
define("ADMIN_URL", DOMAIN . ADMIN_DIR );
}
if(!defined("ADMIN_PATH"))
{
throw new \Exception("Para acessar um módulo do backend você precisa esta no diretorio do admin/");
}
// configura a sessao do usuario
$this->context->set("USER.SESSION", $this->context->get("USER.SESSION") . ADMIN_PATH . "_ADMIN");
// configura o template do ADMIN
// checa se o usuario especificou algum caminho para o template do ADMIN
$templatePath = $this->context->get("CMS.ADMIN.TEMPLATE_PATH");
if(!$templatePath){
$templatePath = ADMIN_PATH;
}
$this->context->setTemplatePath($templatePath); //diretorio raiz de templates?
$this->context->setTemplate($this->context->get('CMS.ADMIN.TEMPLATE')); // seta o template configurado no config.php
// checa se o usuario especificou algum caminho para o template do ADMIN
$templateUrl = $this->context->get("CMS.ADMIN.TEMPLATE_URL");
if(!$templateUrl){
$templateUrl = ADMIN_DIR; // URI do admin: http://localhost/admin/
}
if(!defined("TEMPLATE_URL"))
define("TEMPLATE_URL", $templateUrl . $this->context->TemplateDir() . $this->context->getTemplate() . "/");
}
The files are being called by TEMPLATE_URL:
<link rel="stylesheet" href="<?php echo TEMPLATE_URL ?>static/css/bootstrap.min.css" rel="stylesheet">
I'm still trying to get him to call direct, but without success.
| 7a108ba891d2ad524a9a42c931bf5049f370e8da1f536d53ceb5abecb3bd3f33 | ['93dcd5161a2e414cb9f2fca21dc9e77b'] | I make a form in Wordpress Template that makes certain calculation and displays the result in a modal Bootstrap.
HTML:
//FORM
<form method="post" id="myForm">
<span>Name</span><br><input type="text" name="name" id="name" required>
<span>Email</span><br>
<input type="email" name="email" id="email" required>
<span>Altura</span><br>
<input type="number" name="altura" id="altura" required>
<span>Peso</span><br>
<input type="number" name="peso" id="peso" required>
<br><br>
<button type="submit" id="enviar" onclick="calcularIMC();">Enviar</button>
//MODAL
<div class="modal fade" id="ajax-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div id="corpo_modal">
<p> ALL FIELDS </p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JAVASCRIPT:
function calcularIMC(){
var <PERSON> = document.getElementById("nome").value;
var <PERSON> = document.getElementById("email").value;
var <PERSON> = document.getElementById("estilo").value;
var <PERSON> = document.getElementById("experiencia").value;
var <PERSON> = document.getElementById("altura").value;
var <PERSON> = document.getElementById("peso").value;
var <PERSON> = 5;
var <PERSON> = document.getElementById("corpo_modal");
var <PERSON> = 0;
if(altura >0 && peso >0){
imc = peso / (altura * altura);
}
if(estilo == "Surf"){
if((imc<=25) && (resultado == 5)){
corpo.innerHTML = '<img src="1.png" style="width: 150px; height:150px">';
}
else{
corpo.innerHTML = '<img src="2.png" style="width: 150px; height:150px">';
}
}
else if(estilo == "SUP"){
if((experiencia >= 3) && (imc <=29)){
corpo.innerHTML = '<img src="3.png" style="width: 150px; height:150px">';
} else{
corpo.innerHTML = '<img src="4.png" style="width: 150px; height:150px">';
}
}
}
The problem is that when I send the form, it updates the page and does not display the modal.
After some research, I found that to solve this problem I will need to use Ajax - jQuery.ajax.
I found this code:
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
When I create a form in a SEPARATE page without putting in wordpress template, it works. But when I put the code in wordpress template it updates the page after 3 seconds.
I also discovered that I can use a native function ajax in jquery, the function $.ajax(); and inside of oneself I use tags like url, type, data and so on. I'm a beginner in Ajax and I'm lost on how to do this.
Why the function e.preventDefaul(); not works when I put in wordpress template?? It's possible make it work in wordpress template?
or
How I can use the $.ajax() to solve this problem??
I want send the form without refresh the page!
|
7bf364bc07c66da91da21db37661fa8e0d14166cecb08a71c38124e3976615e9 | ['93e452731a4b48e2a2226a1208a1bc2e'] | Via assistance received from Datatables.net forum.
var startdate;
var enddate;
$.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex) {
if (typeof startdate === 'undefined' || typeof enddate === 'undefined') {
return true;
}
var coldate = moment(aData[3], 'DD-MM-YYYY');
console.log('coldate', coldate)
var valid = true;
if (coldate.isValid()) {
if (enddate.isBefore(coldate)) {
console.log('enddate before coldate', enddate)
valid = false;
}
if (coldate.isBefore(startdate)) {
console.log('coldate before startdate', startdate)
valid = false;
}
} else {
valid = false;
}
return valid;
});
jQuery(document).ready(function ($) {
var table;
$.ajax({
url: "table.json",
dataType: "jsonp", // jsonp
type: "POST",
jsonpCallback: 'processFunction', // add this property
contentType: "application/json; charset=utf-8",
success: function (result, status, xhr) {
table = $('#poview').DataTable({
initComplete: function () {
this.api().columns([1]).every( function () {
var column = this;
var select = $('<select class="custom-select custom-select-sm rowSort"><option value="">Trans Type</option></select>')
.appendTo( $('#rowSort' ))
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
} );
});
$('#poview_info').appendTo($('#sumInfo'));
$('#poview_paginate').appendTo($('#pageInfo'));
},
"pagingType": "first_last_numbers",
"scrollX": true,
fixedHeader: true,
fixedColumns: {
leftColumns: 2
},
"bAutoWidth": true,
sDom: 't<i><""p>',
data: result,
columns: [
{ data: 'policy number' },
{ data: 'transaction type' },
{ data: 'transaction date' },
{ data: 'transaction effective date' },
{ data: 'minimum premium amount' },
{ data: 'deferred premium amount' },
{ data: 'total written premium' },
{ data: null,
className: "center actionItem",
defaultContent: '<button class="btn actionIcon" data- toggle="modal" data-target="#modal-1"><i class="fas fa-calculator"></i></button>'}
],
columnDefs: [{
targets: -1,
className: 'dt-nowrap',
className: 'dt-left'
}],
"pageLength": 5
});
$('#reportrange').daterangepicker({
locale: { "format": "MM/DD/YYYY",
"separator": " - ",
"applyLabel": "Apply",
"cancelLabel": "Cancel",
"fromLabel": "From",
"toLabel": "To",
"firstDay": 1},
"opens": "right",
"startDate":startdate,
},
function (start, end, label) {
console.log('New date range selected: ' + start.format('YYYY-MM-DD')
+ ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
});
},
error: function (xhr, status, error) {
console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText);
}
});
$('#reportrange').on('apply.daterangepicker', function (ev, picker) {
startdate = moment(picker.startDate.format('DD-MM-YYYY'), 'DD-MM-YYYY');
enddate = moment(picker.endDate.format('DD-MM-YYYY'), 'DD-MM-YYYY');
table.draw();
});
});
| b4de6e1d7028f8df1fbca8abdfb55ac67b865f47c9f97d615b54df72cb81d0a2 | ['93e452731a4b48e2a2226a1208a1bc2e'] | I need to use this date range picker with my datatables as per a business requirement. Although, a typical usage of my date range sorting and search can be seen here. https://jsfiddle.net/zy914ko6/
I need help with how to produce minimum and maximum values to have the implementation fit the required jQuery script to draw the table. FMI: I am using serverside ajax and json on my production. So far my tables are running and I do get a draw but it doesn't reflect the "effective date [3]" column.
My "somewhat" working application can be viewed here
http://live.datatables.net/pexopupu/1/edit]1
The sample of the code i used for my daterangepicker is seen here:
var table_1 = $('table.display#tb_posts').DataTable({
"processing": true,
"serverSide": true,
"ajax" : {
"url" : "{{ route('posts.list') }}",
"type" : "GET"
},
"columns": [
{data: 'check', name:'id', className: 'text-center' },
{data: 'DT_Row_Index', name:'DT_Row_Index', className: 'text-right' },
{data: 'id', name: 'posts.id', className: 'text-right' },
{data: 'title', name: 'posts.title'},
{data: 'username', name: 'users.username'},
{data: 'created_at', name: 'posts.created_at'},
],
"autoWidth": true,
"order": [[ 3, 'asc' ]],
"sDom": "B<<'span8'f>r>t<<'col-sm-4'i><'col-sm-8'p>>",
"pagination": true,
"pagingType": "full_numbers"
});
//DateRangePicker
var startdate;
var enddate;
$('#reportrange').daterangepicker({
locale: { format: 'DD/MM/YYYY' },
ranges: {
'All dates' : [moment().subtract(10, 'year'), moment().add(10, 'year')],
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'7 last days': [moment().subtract(6, 'days'), moment()],
'30 last days': [moment().subtract(29, 'days'), moment()],
'This month': [moment().startOf('month'), moment().endOf('month')],
'Last month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
"opens": "left",
"applyClass": "btn-primary",
"showDropdowns": true,
},
function (start, end, label) {
var s = moment(start.toISOString());
var e = moment(end.toISOString());
startdate = s.format("YYYY-MM-DD");
enddate = e.format("YYYY-MM-DD");
});
//Filter the datatable on the datepicker apply event
$('#reportrange').on('apply.daterangepicker', function (ev, picker) {
startdate = picker.startDate.format('YYYY-MM-DD');
enddate = picker.endDate.format('YYYY-MM-DD');
$.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex) {
if (startdate != undefined) {
var coldate = aData[3].split("/");
var d = new Date(coldate[2], coldate[1] - 1, coldate[1]);
var date = moment(d.toISOString());
date = date.format("YYYY-MM-DD");
dateMin = startdate.replace(/-/g, "");
dateMax = enddate.replace(/-/g, "");
date = date.replace(/-/g, "");
if (dateMin == "" && date <= dateMax) {
return true;
} else if (dateMin == "" && date <= dateMax) {
return true;
} else if (dateMin <= date && "" == dateMax) {
return true;
} else if (dateMin <= date && date <= dateMax) {
return true;
}
return false;
}
});
table_1.draw()
});
Can you help me reach a solution...
I'm not sure where I went wrong.
|
e8373023cfdf040b39e31d822913feb45edc1b49c6f468fc11f6df52b4d48653 | ['93f07b6f141d42df9573f0657763e0ba'] | Im trying to style a plugin in my Django-CMS project ( django 1.11, CMS 3.6.0 ).
Im trying to add my class to my plugin html, like this :
<div class="question">
<h1 class="question-title">{{ instance.poll.question }}</h1>
<form action="{% url 'polls:vote' instance.poll.id %}" method="post">
{% csrf_token %}
<div class="form-group">
{% for choice in instance.poll.choice_set.all %}
<div class="radio">
<label>
<input type="radio" name="choice" value="{{ choice.id }}">
{{ choice.choice_text }}
</label>
</div>
{% endfor %}
</div>
<input type="submit" value="Vote" />
</form>
</div>
Then I go into my css, and try to apply some styles to the plugin, but nothing happens. When I inspect my div which should have a class of "question" in the browser, there is no class even though I specified it in my html. Why is that ?
When I do something like :
body {
width: 1060px;
margin: 10px auto;
}
It applies the styles correctly.
Anybody knows what is happening here ? Where are my custom classes from the html ?
I was trying to find a guide on Django-CMS and styling, but Im not having much luck.
Thank you guys !
| c4a60f4903f08813c96e5f433ff8650aa5a6ed09041feffb387bd011465ccb5c | ['93f07b6f141d42df9573f0657763e0ba'] | Im a newbie working on a news site (or at least trying to, a lot of "problems" in the last few days lol ) trying to learn Django the best I can.
This is what I want to do :
I have an Article Model, it used to have 6 image fields that I used to send to the template and render the images, each image field had its own name and all was well in the world.
Then I got tasked with puting the Article images in a separate Image model.
So I did this :
class Article(models.Model):
title = models.CharField('title', max_length=200, blank=True)
slug = AutoSlugField(populate_from='title', default="",
always_update=True, unique=True)
author = models.CharField('Author', max_length=200, default="")
description = models.TextField('Description', default="")
is_published = models.BooleanField(default=False)
article_text = models.TextField('Article text', default="")
pub_date = models.DateTimeField(default=datetime.now, blank=True)
article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="")
def __str__(self):
return self.title
class ArticleImages(models.Model):
article = models.ForeignKey(Article, on_delete="models.CASCADE", related_name="image")
image = models.ImageField("image")
name = models.CharField(max_length=50, blank=True)
But so far I wasnt able to access my images in my template using
{{ article.image.url }} or {{ article.image.image.url }}
or any other combination. Why is that ?
Did I set up my models correctly ? One person suggested that I should change the model field from ForeignKey to OneToOneField, but I didn't get much feedback on why and how ?
So, how would I make a for loop that loops through the Articles model and then gets the related images for each Article ? I essentially want it to behave like I still have the 6 different fields like I did before. ( I have to do it this way, it's a part of the task ).
here are my views and my "index" template that I used to loop through the Articles and display 6 latest news on my home page. (please ignore the tags,I am aware they aren't working like this..the template is just so you can understand what I am talking about )
my views.py:
class IndexView(generic.ListView):
template_name = 'news/index.html'
context_object_name = 'latest_article_list'
def get_queryset(self):
return Article.objects.all()
class CategoryView(generic.ListView):
template_name = 'news/categories.html'
context_object_name = 'category'
def get_queryset(self):
return Article.objects.filter(article_category__category_title="Politics")
class ArticlesView(generic.ListView):
context_object_name = 'latest_article_list'
template_name = 'news/articles.html'
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(ArticlesView, self).get_context_data(**kwargs)
context['categories'] = Category.objects.all()
return context
def get_queryset(self):
category_pk = self.request.GET.get('pk', None)
if category_pk:
return Article.objects.filter(article_category__pk=category_pk).order_by("-pub_date")
return Article.objects.order_by("-pub_date")
def article(request, article_id):
article = get_object_or_404(Article, pk=article_id)
context = {'article': article,
'article_category': article.article_category.category_title}
return render(request, 'news/article.html', context)
template that I used with my old model :
{% for article in latest_article_list %}
<img class="single-article-img" src="{{ article.image.name.url }}" alt="">
<div class="container row">
<!-- Start Left Blog -->
<div class="article mt-10 col-md-4 col-sm-4 col-xs-12">
<div class="single-blog" style="margin:10px auto;">
<div class="single-blog-img">
<a href="{% url 'news:article' article.id %}#article-title">
<img class="for-imgs" src="{{ article.image.url }}" alt="">
</a>
</div>
<div class="blog-meta">
<span class="date-type">
<i class="fa fa-calendar"></i>{{ article.pub_date }}
</span>
</div>
<div class="xx blog-text">
<h4>
<a href="{% url 'news:article' article.id %}#article-title">{{ article.title }}</a>
</h4>
<p>
{{ article.description|truncatewords:30 }}
</p>
</div>
<span>
<a href="{% url 'news:article' article.id %}" class="ready-btn">Read more</a>
</span>
</div>
</div>
{% endfor %}
Thank you !
|
1120ab1994b0800d96d72bb8494f687c1ae40badb2c7fbdcd15d8d8f1a5b359b | ['93fa03ba39b041238a5a3970f954608c'] | Besides using tuples or wrapping Object in a new datatype, another option is to parameterize Object with a type variable:
data Object v =
Object { location <IP_ADDRESS> (Double, Double)
, shape <IP_ADDRESS> Shape
, velocity <IP_ADDRESS> v } deriving (Functor)
When passing an object to the renderer, you could "mute" the velocity by storing a (), using void myObject or perhaps using a polymorphic update like myObject { velocity = () }.
| fbe6b01a55ad6d24f5f5f8d07fe0b5693a977b20af75132168fc87d00a0d81a8 | ['93fa03ba39b041238a5a3970f954608c'] | I didn't, but the suggestion above from <PERSON> seems to suggest that rc.local is being executed. Perhaps it would be more accurate of me then to say that rc.local is being executed, but I am not getting the results that I expect (ifconfig eth0:0 <IP_ADDRESS> netmask <IP_ADDRESS> broadcast <IP_ADDRESS><PHONE_NUMBER> broadcast <PHONE_NUMBER>), which I appreciate is something very different. |
ea9c324cfa72c5a39c1174254e3dc3f501d33aceabae80174b2e47007fd690d3 | ['94021be3ff534ac39f924b16b86555db'] | Question:
Let $X$ be a set and $d$ the distance function on $X$ defined by $d(x,x)=0$, $d(x,y)=1$ for $x \neq y$. Prove that each subset of $(X,d)$ is open.
I'm having trouble finishing up this proof, here is what I have so far.
Proof:
Let $U\subset X$. To show that $U$ is open, we must show that $U$ is a neighborhood of all of its points, that is, there is a $\delta >0$ such that:
$B(a;\delta) \subset U$ for some $a \epsilon X$
Since $d(x,x)=0$, we know that $x \epsilon B(a;\delta)$ if $x=a$.
-- Here is where I am stuck. I want to just choose $\delta >1$ but then that would mean my open ball would no longer be contained in $U$ (or would it?). If I can find a way to incorporate $d(x,y)=1$, then I could just finish the proof by stating that since $B(a;\delta)$ is a neighborhood of its points, and $B(a;\delta) \subset U$, then that implies the $U$ is also a neighborhood, hence U is open.
| a1b128526d78e3669d46bf17e6b837d618740d4e0cf941a198a6febde7a85998 | ['94021be3ff534ac39f924b16b86555db'] | In <PERSON>'s Analysis, he says that an open set in $\mathbb{R}^1$ is no longer an open set if it is considered a subset of $\mathbb{R}^2$ because such a set cannot contain a 2-ball. I am having trouble understanding how an open interval in $\mathbb{R}^1$ can ever be a subset of $\mathbb{R}^2$. Also, does the same apply for open sets in $\mathbb{R}^n$ as subsets of $\mathbb{R}^{n+1}$?
|
356b5c8dbffb20c3949035d71b7579b7ff35941337631081aa8606a5fcd09df1 | ['940c1f87b3a8454aa31733c6b6fd1843'] | FINSEC, I honestly can't tell if it's "crashing" (as in ceasing to be loaded), but it stops responding to page requests. The process list shows the Apache instances are loaded in memory, which is where I'm finding things to be strange.
cjc, I'll look in those logs and see if there's anything that seems hinky. Thnks! | ead918e83e9b16c6ddff9b1750c133ee143bfc92d1c36408c865ccf0851c2728 | ['940c1f87b3a8454aa31733c6b6fd1843'] | 'archivedDataWithRootObject:' is a class method, whereas 'setOutputFormat' is an instance method. From the documentation for 'archivedDataWithRootObject:':
An NSData object containing the encoded form of the object graph whose root object is rootObject. The format of the archive is NSPropertyListBinaryFormat_v1_0.
What you need to do is create an NSKeyedArchiver, and encode the root object. Also, make sure that all the contents of your collection implement 'encodeWithCoder' and 'initWithCoder'. See
Encoding and Decoding Objects
The problem with this approach is you have to manually assign keys for each object you encode, which it doesn't sound like what you want, since you already have a collection. Both Arrays and Dictionaries contain methods to write to an xml file, which is a much easier approach.
[artistCollection writeToFile:@"/Users/fgx/Desktop/stuff" atomically:YES];
Discussion on this method (for both NSDictionary and NSArray):
If the receiver’s contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the file written by this method can be used to initialize a new array with the class method arrayWithContentsOfFile: or the instance method initWithContentsOfFile:. This method recursively validates that all the contained objects are property list objects before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.
Blockquote
|
efa85b6a4c6abfb82e852f6ed4dbbb8b9dc2cf63d7429b1264eb0820f48fd838 | ['941177e8099f422a8f493147435fb06d'] | it was a router problem
could tell because i could connect to other wifi signals
connected to my router with a wired connection and reset everything (except for full factory reset) in the diagnostics menu
router is a 2wire (router IP: <IP_ADDRESS>)
i found the router settings via the browser http://
| 681c6c90e662f12914a95c0eaf124dde569db94a14b664b9a85cab7f476feaf1 | ['941177e8099f422a8f493147435fb06d'] | Using Ubuntu 14.04, very frequently when I use two-finger scroll it switches between programs (alt+tab equivalent) and this is super annoying! How can I keep two-finger scroll but not have it switching programs/windows on me all the time??
(Further info: I am using an Asus x501a refurbished laptop with a large, button-less trackpad with the right and left click seamless but designated in the bottom ~1/2" of the pad area, pad size approx. 3x3", I have both tap-to-click and 2-finger scroll enabled, natural scrolling is disabled, medium pointer-speed and double-click)
|
0833aae0fdb0a3e115eceeef183e290fd4cea4c16602e2ccd0870c0d075463cc | ['9426ab1ead9c44fba672059e4dc6d90c'] | Using Wacom Intuos Pro Tablets, (Paper in my case):
When editing photos or images using Gimp, Photoshop, etc., I find it helpful to be in "Pen Mode".
But, in vector graphics, I prefer "Mouse Mode", like with Inkscape or Illustrator.
Also, when testing 3D rendering, (like quickly moving a 3D camera in a game), Mouse Mode also seems much more efficient.
Is there a way to toggle between "Pen Mode" and "Mouse Mode" quickly, by binding that function to the eraser, express keys, display keys, or even a keyboard shortcut?
Is there a way to create a custom macro for this - if it isn't supported "out-of-the-box"?
Personal Work-Around:
I have been creating separate application configuration settings using the Wacom Settings control panel, which allows either pen or mouse mode to be set for an application.
Caveat: It is often the case that I want to switch within the SAME application, and this workaround doesn't seem to work for this.
| bc5ad0ab1f6d170d37c0b5a27372107430dcd5b756eae18c3ff29c7325a96010 | ['9426ab1ead9c44fba672059e4dc6d90c'] | @Cybernetic this is what I found on [Wikipedia](https://en.wikipedia.org/wiki/NP-completeness), so it seems like NP-Hard is more universal, since we reduce NP-Complete `G` to NP-Hard `H`.
```
Another definition is to require that there be a polynomial-time reduction from an NP-complete problem G to H.[1]:91 As any problem L in NP reduces in polynomial time to G, L reduces in turn to H in polynomial time so this new definition implies the previous one. Awkwardly, it does not restrict the class NP-hard to decision problems, and it also includes search problems or optimization problems.
``` |
00b3dcea0a841bd9d9c3e143a672e9143f00e0409b03e6ecd04b420c098cb744 | ['942a49fe111c44158413fc002ff86541'] | In UPDATE and DELETE statements all the primary key columns must be restricted and the only allowed restrictions are:
the single-column = on any partition key or clustering columns
the single-column IN restriction on the last partition key column
CASSANDRA-6237 addresses part of those limitations in Cassandra 3.0.
See this post at DataStax dev blog for more info: A deep look at the CQL WHERE clause.
| 9808fe54518e609c1925a6bd34140566799f2dd0f85cbf09d610ee4a27deb727 | ['942a49fe111c44158413fc002ff86541'] | <PERSON> tipo:
Scanner ler = new Scanner(System.in);
String answer = "";
do {
double n1, n2;
System.out.println("Digite o valor da nota 1 e da nota 2: ");
n1 = ler.nextDouble();
n2 = ler.nextDouble();
double nf = (n1 + n2) / 2;
System.out.printf("Nota final = %.2f \n", nf);
if (nf < 6) {
System.out.println("Reprovado.");
} else {
System.out.println("Aprovado.");
}
System.out.println();
System.out.println("Deseja continuar (sim/nao)?");
answer = ler.next();
System.out.println();
} while (answer.equalsIgnoreCase("sim"));
|
8bb852048af082d81872bccb841c2b1911fcfc625fe6320a24111fd135169544 | ['94415f72ce7c4ac890f32f6cb6012fbc'] | How do I increase the space between each bar with matplotlib barcharts, as they keep cramming them self to the centre. (this is what it currently looks)
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def ww(self):#wrongwords text file
with open("wrongWords.txt") as file:
array1 = []
array2 = []
for element in file:
array1.append(element)
x=array1[0]
s = x.replace(')(', '),(') #removes the quote marks from csv file
print(s)
my_list = ast.literal_eval(s)
print(my_list)
my_dict = {}
for item in my_list:
my_dict[item[2]] = my_dict.get(item[2], 0) + 1
plt.bar(range(len(my_dict)), my_dict.values(), align='center')
plt.xticks(range(len(my_dict)), my_dict.keys())
plt.show()
| 5356448aa7030b1927d55be5e354647fea4020de979bf2523ae8ba533f82029e | ['94415f72ce7c4ac890f32f6cb6012fbc'] | C:\Python34\Scripts>pip install Gooey
Collecting Gooey
Using cached Gooey-<IP_ADDRESS>.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Haeshan\AppData\Local\Temp\pip-build- 5waer38m\Gooey\setup.py", line 9, in <module>
version = __import__('gooey').__version__
File "C:\Users\Haeshan\AppData\Local\Temp\pip-build-5waer38m\Gooey\gooey\__init__.py", line 2, in <module>
from gooey.python_bindings.gooey_decorator import Gooey
File "C:\Users\Haeshan\AppData\Local\Temp\pip-build-5waer38m\Gooey\gooey\python_bindings\gooey_decorator.py", line 54
except Exception, e:
^
SyntaxError: invalid syntax
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in
C:\Users\Haeshan\AppData\Local\Temp\pip-build-5waer38m\Gooey\
this error is appearing when I try to install the Gooey module for python, any ideas why?
|
4fe9f06f23d2490a63c5a27fa975eeeab043213d8c3ab1d1e74093aee1e1f251 | ['946d6ac419374c06821a9ce3c356d7d8'] | It seems like they actually use a TextInputLayout wrapping up an AutoCompleteTextView. Note that they are already the material Components theme [https://github.com/material-components/material-components-android/blob/master/docs/getting-started.md].
See:
https://material.io/design/components/menus.html#exposed-dropdown-menu
https://material.io/develop/android/components/menu/
| 2739c90308afa6c2fe1276c4275037735bc438a26224dacddf11b4dcba924cbc | ['946d6ac419374c06821a9ce3c356d7d8'] | I found <PERSON>'s answer super helpful. However, I ran into a problem when I tried to add an OnClickListener to each tab. I needed each page to open a different URL link. I modified the code to hide the views that are out of sight and added a little extra effect to slide the view at .5 the speed:
public void transformPage(View view, float position) {
if (position <= -1.0F || position >= 1.0F) { // [-Infinity,-1) OR (1,+Infinity]
view.setAlpha(0.0F);
view.setVisibility(View.GONE);
} else if( position == 0.0F ) { // [0]
view.setAlpha(1.0F);
view.setVisibility(View.VISIBLE);
} else {
// Position is between [-1,1]
view.setAlpha(1.0F - Math.abs(position));
view.setTranslationX(-position * (view.getWidth() / 2));
view.setVisibility(View.VISIBLE);
}
}
|
f75b4748cb90edf71fca056676ff20fb1656f3db7e1442599d24af8001f3de7e | ['94701f4a47154f5a917ca8041304df06'] | "индексировать колонку sid не нужно, записей там много быть не должно, так как сессионные данные, обычно, хранятся в течение нескольких часов, после чего удаляются функцией сборщика мусора."
Неа. Тут будет учитываться галочка "запомнить меня", собственно это одна из причин почему механизм "сессий" должен быть самописанным(занулять session.gc_probability - не вариант, конечно) | cb500676a35a0a6ba92460642e6020c62859470c9e7a217c37d35b2a19fe02d2 | ['94701f4a47154f5a917ca8041304df06'] | Если верно то, что вы написали, т.е. "подставляется реферер из заголовка..." и "допустим, она не кодируется, передается прямой текст ...", то создаете скрипт `site/1.html`, где будет `" width="1" height="1">` и другой скрипт `site/2.html`, где будет ``. И чтобы украсть куки у пользователя достаточно ему перейти по `site/1.html`. Напоминаю, chrome может и не выполнить скрипт из-за xss auditor'а. |
30889eb82a56ca9c5033dcc043e0bc8cc15b1df089731ac96d684b19c228eb63 | ['94840d792790477696886ee6fe108fc7'] | I had the same problem.
OS 10.9.5 running Server 3.2.2
The answer was install 10.10.5 one way or another (purchases tab from app store is best if available). This will stop 3.2.2 from working in the meantime.
Then buy latest Server 5.x on another mac running something new like Sierra using the same apple ID.
Then install it on the older mac from the purchases tab will give you 5.0.15 which can upgrade and bring across settings from 3.2.2
Then install Sierra and do the upgrade to the latest 5.x
| 6469a9ad1446383e30fb4d58d05bf243982f0813b4d77baf2d0b8f6068586553 | ['94840d792790477696886ee6fe108fc7'] | Besides googling for possible solutions to this problem and trying them out (hoping that they help), here is an advice how to diagnose what causes this. The steps below apply to Xcode 4.2.
In menu, select View > Navigators > Show Log Navigator. The Log Navigator should be displayed on the left side.
In the list of builds, select the one that causes troubles. The log from the build will be shown in the main view.
Scroll to the very bottom. The last two steps should be CodeSign and Validate, where the Validate step contains the warning.
Expand CodeSign and inspect the parameters used to perform the code signing.
Expand Validate to learn more about the errors/warnings.
Also scroll up and inspect the heading for the build target:
Build Target (your build target)
Project (your project) | Configuration (selected configuration) | Destination ...
In my case, I found out that while doing the Archive build, the app was signed with the developer certificate. Inspecting the heading for the build target revealed that the Release configuration was used to build the archive. The remedy was to:
In the menu, select Product > Edit Scheme
In the Edit Scheme dialog, select the Archive build item (list on the left)
Change Build Configuration to Distribution
I had this issue after duplicating a build target. The original target was signed by the distribution certificate. However, when copying the target, Xcode decided to assign the Release configuration to the Archive build.
|
6ff68e5feead5fa72d86a7d6acfefd14dba165e49f15f806d8ab89fc3e344fbd | ['94875ed4ec174c12b632d0ab9b345b49'] | I am trying to implement this solution but it seems that my model tries to fit the missing data (which I set to -1 as you suggested in 3). Do you guys have a working example? For example, is it ok to use .fit(..,shuffle=False, validation_split=0.1)? There are several posts on StackOverflow having trouble with sample_weight, incl. mine https://stackoverflow.com/questions/63744387/using-sample-weight-in-tensorflow | 3365de7ce9bfdb83ed024dd5b37f148f8a378e5557326a1101181a55d9354111 | ['94875ed4ec174c12b632d0ab9b345b49'] | not sure if its coincidence but i waited until i grabbed a shark's attention and then stopped swimming, faced the shark and repeatedly pressed the B(counter) button as the shark approached. using this method i was able to get the same shark to attack me 4 times within 5 minutes
|
1b795675975641b9fb578d667d110ecf3573a59491dc1af65037d78b903fa5c4 | ['948865debb6742b6ac3c3503df10c65f'] | init isn't run until you make an instance of the class. To access:
class ClassName(object):
def __init__(self):
self.variable = "value"
instance = ClassName()
print(instance.variable)
I'm not sure what you're trying to do here but the thing to remember is that those data members declared in init don't exist until you make an instance of the class.
| 0f81c77efc6360ff81e9c4bd9436d7d3c19a15b69d374f9d903ac2cb4dc0f832 | ['948865debb6742b6ac3c3503df10c65f'] | I had a similar problem that I solved by calling the program that I was trying to connect to over telnet in a pexpect spawn class and the telnet project miniboa. By wrapping the program in pexpect you can the read and write to stdin/stdout safely.
To use the input function, pexpect uses regular expressions to know when to stop reading and get input, so I added '>' to the end of my read from stdin function.
class Client(object):
def __init__(self, client):
self.client = client
self.process = pexpect.spawnu(PROGRAM)
def on_connect(client):
clients.append(Client(client))
def process_clients():
"""
Check each client, if client.cmd_ready == True then there is a line of
input available via client.get_command().
"""
for client in clients:
if client.active and client.cmd_ready:
# If the client sends input echo it to the chat room
interact(client)
def interact(client):
choice = client.process.expect([re.compile('\n*/>$'), '\n'])
if choice == 1: # not an input prompt
if len(client.process.before) == 0:
return
client.client.send(client.process.before+'\n')
else: #input
msg = client.client.get_command().strip()
client.process.sendline(msg)
if __name__ == "__main__":
tn = miniboa.TelnetServer(
port=7000,
address='<IP_ADDRESS>',
on_connect = on_connect
)
while True:
tn.poll()
if len(clients) > 0:
process_clients()
PROGRAM is the program to be called. This is mostly gleaned from the miniboa examples.
|
e050985bc7a1892520bf37796494d20c147eec9ebaed9b328c327ded96971447 | ['948fe5eacfe84fa090884e9b48ffcc4d'] | Backstory: I'm creating an application using Electron and am currently attempting to run a function when the computer is locked/unlocked.
After much trial and error I finally managed to get the following python code working. The code prints either Locked or Unlocked on the screen when the relevant codes are fired. I now need to run the python script from Node JS so that I can run more functions when the events fire.
import win32con
import win32gui
import win32ts
import time
print("Test")
WM_WTSSESSION_CHANGE = 0x2B1class WTSMonitor():
className = "WTSMonitor"
wndName = "WTS Event Monitor"
def __init__(self):
wc = win32gui.WNDCLASS()
wc.hInstance = hInst = win32gui.GetModuleHandle(None)
wc.lpszClassName = self.className
wc.lpfnWndProc = self.WndProc
self.classAtom = win32gui.RegisterClass(wc)
style = 0
self.hWnd = win32gui.CreateWindow(self.classAtom, self.wndName,
style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT,
0, 0, hInst, None)
win32gui.UpdateWindow(self.hWnd)
win32ts.WTSRegisterSessionNotification(self.hWnd, win32ts.NOTIFY_FOR_ALL_SESSIONS)
def start(self):
win32gui.PumpMessages()
def stop(self):
win32gui.PostQuitMessage(0)
def WndProc(self, hWnd, message, wParam, lParam):
if message == WM_WTSSESSION_CHANGE:
self.OnSession(wParam, lParam)
def OnSession(self, event, sessionID):
if event == 7:
print("Locked")
if event == 8:
print("Unlocked")
print(event)
myststa(event)
WTSMonitor().start()
The Node code:
const { spawn } = require('child_process');
let py = spawn('python',['locked.py'])
py.stdout.on('data', data => console.log('data : ', data.toString()))
py.on('close', ()=>{
})
When I run python from the console using "Python locked.py" I see the test message printed. However, when running using node locked.js the script looks like it's running but never prints to the console.
The other thing to mention is that if I comment out the final line WTSMonitor().start() then I can see the test message print to the node console.
| 256b080b5f14688e4d3663b4d16022ffd8e16746c6bfef0bb1eaf16184ac1f9c | ['948fe5eacfe84fa090884e9b48ffcc4d'] | The method I would use to solve this is to fire an async function within the scrape view.
@shared_task
def do_the_needful():
return "hello I am doing the needful"
def scrape_result(request, scrape_id):
result = AsyncResult(scrape_id).get()
# convert result to json or some other web format
return result_as_json
def scrape(request):
scrape_request_id = do_the_needful.submit()
return render(request, "scrape.html", context={"scrape_request_id": scrape_request_id}
Then within the HTML you'll need to create some Javascript which will perform Ajax requests to the scrape_result view using the scrape_request_id in the context.
|
0191b0b7acc3412f3f978119a6e6f66eed9276e0dce30934bc9b731326719038 | ['9497d1048e7b460a95484b0922e798f5'] | I'm not sure if there's a library function to do this, but here's a sketch of a solution using “async” that assumes uninteresting answers will raise an exception.
racing <IP_ADDRESS> [Async a] -> IO a
racing actions = do
first <- waitAnyCatch actions
case first of
(action, Left _) -> racing (delete action actions)
(action, Right a) -> mapM_ cancel (delete action actions) >> return a
| 8470b016c70b95e60cf4aabc8b2b504cc57edc5e9216d4bf9114d938294a9147 | ['9497d1048e7b460a95484b0922e798f5'] |
It seems like servant providing a new defaultServices for every request.
It is, because your code as written is an STM action to do so. Following the logic—
defaultServices <IP_ADDRESS> ServiceSet
defaultServices = newTVar ...
This (fragmentary) definition crucially does not run the STM action to produce a new TVar. Instead it defines a value (defaultServices) which is an STM action which can produce TVars. Following where defaultServices gets passed to, you use it in your handlers like—
getService = do
stm <- ask
liftIO . atomically $ do
tvar <- stm
...
The action stored in your Reader is unchanged from the defaultServices value itself, so this code is equivalent to—
getService = do
liftIO . atomically $ do
tvar <- defaultServices
...
And by substituting in the definition of defaultServices—
getService = do
liftIO . atomically $ do
tvar <- newTVar ...
...
This now looks obviously wrong. Instead of defaultServices being an action to produce a new TVar, it should be that TVar itself, right? So on the type level without aliases—
type ServiceSet = STM (TVar (M.Map String MicroService)) -- From this
type Services = TVar (M.Map String MicroService) -- To this
defaultServices <IP_ADDRESS> Services
Now defaultServices represents an actual TVar, instead of a method of creating TVars. Writing this may seem tricky if it's your first time because you somehow have to run an STM action, but atomically just turns that into an IO action, and you probably “know” that there is no way to escape IO. This actually is incredibly common though, and a quick look at the actual stm documentation for the functions in play will point you right to the answer.
It turns out that this is one of those exciting times in your life as a Haskell developer that you get to use unsafePerformIO. The definition of atomically spells out pretty much exactly what you have to do.
Perform a series of STM actions atomically.
You cannot use atomically inside an unsafePerformIO or
unsafeInterleaveIO. Any attempt to do so will result in a runtime
error. (Reason: allowing this would effectively allow a transaction
inside a transaction, depending on exactly when the thunk is
evaluated.)
However, see newTVarIO, which can be called inside unsafePerformIO,
and which allows top-level TVars to be allocated.
Now there's one final piece of this puzzle that isn't in the documentation, which is that unless you tell GHC not to inline your top-level value produced using unsafePerformIO, you might still end up with sites where you use defaultServices having their own unique set of services. E.g., without forbidding inlining this would happen—
getService = do
liftIO . atomically $ do
mss <- readTVar defaultServices
getService = do
liftIO . atomically $ do
mss <- readTVar (unsafePerformIO $ newTVarIO ...)
...
This is a simple fix though, just add a NOINLINE pragma to your definition of defaultServices.
defaultServices <IP_ADDRESS> Services
defaultServices = unsafePerformIO $ newTVar M.empty
{-# NOINLINE defaultServices #-}
Now this is a fine solution, and I've happily used it in production code, but there are some objections to it. Since you're already fine with using a ReaderT in your handler monad stack (and the above solution is mostly for people who for some reason are avoiding threading a reference around), you could just create a new TVar at program initialization and then pass that in. The briefest sketch of how that would work is below.
main <IP_ADDRESS> IO ()
main = do
services <- atomically (newTVar M.empty)
run 8080 $ serve Proxy (server services)
server <IP_ADDRESS> TVar Services -> Server Api
server services = enter (readerToHandler services) serverT
getService <IP_ADDRESS> LocalHandler (Maybe MicroService)
getService = do
services <- ask
liftIO . atomically $ do
mss <- readTVar services
...
|
f5573aef90370a96d9341fbb7eb9aa5417ad6fdf78ab9ad100a107e08e50230f | ['949c3436e58144afbfd32edf5b6edf61'] | In an asset definition you can have a field, allowed_viewer field and based on that you can have define rules to view the asset
Example
In the cto file,
asset Commodity identified by tradingSymbol {
o String tradingSymbol
o String description
o String mainExchange
o Double quantity
o Trader[] allowed_viewer
--> Trader owner
}
In acl file
rule R1a_Traderview {
description: "Everyone in allowed_viewer can view"
participant(p): "org.example.trading.Trader"
operation: READ
resource(r): "org.example.trading.Commodity"
condition: (r.allowed_viewer.indexOf(p.getIdentifier())>=0)
action: ALLOW
}
| a0e6801d32ba52fc1d2c4acdf0baaa08aa9af67a547490b1efc063595a86f952 | ['949c3436e58144afbfd32edf5b6edf61'] | I am developing an android app completely native using only c++.
But I am not able to find a way to run some native code ,when a sms arrives. In java I can do it through broadcast receiver .But not able to find any method for ndk.
Or any suggestion how can i use broadcast receivers to run native code
|
a6d15496e3377739db3ea80250e1c5a035b9a2793e48a56af3a8eef574ed9543 | ['94a7d10ab51d400ab5fe3dbde8797455'] | I extract multiple reports daily and they all start with the word "report". They all have the same amount of columns just different amount of rows. What I have created is a sub that will loop through all open workbooks with the name "report" in the beginning and grab the data to put in consecutive order in my master workbook "Distribution"
I have the macro doing exactly what I need it to do but I am looking for guidance to make it more dynamic. The Header row I am copying every time and if a new column is added it wouldn't be captured. Same with the rows.
I am still fairly new to VBA but I think I am starting to understand more and more. Sorry for all the commented sections. Any helpful pointers would be greatly appreciated.
Private Sub CommandButton3_Click()
'Get Data button
Dim wbk As Workbook
Dim wsh As Worksheet
Dim nrow As Long
Set wsh = ActiveWorkbook.Worksheets("Data")
screen 0 'turns off calculation and screen updating
nrow = 2
For Each wbk In Workbooks
If Left(wbk.Name, 6) = "report" Then
wbk.Worksheets(1).Range("A1:Z1").Copy _ 'copies the header row
Destination:=wsh.Range("A1") 'paste data in row 1
wbk.Worksheets(1).Range("A2:Z500").Copy _ 'copy the rest of the
Destination:=wsh.Range("A" & nrow) 'paste data next available row
wbk.Close False
nrow = wsh.UsedRange.Rows.Count + 1 'Next row to paste next sheet into
End If
Next wbk
nrow = 0 ' reset next row
FilterData 'Function to filter unwanted data
screen 1 'Turn on screen updating and calculation
End Sub
| 5f3cc5fe8744924247dd105c70cf20cc38869c1c6ab119791898c6c5dfa4cc76 | ['94a7d10ab51d400ab5fe3dbde8797455'] | I currently have an HTML form that I have put together that takes the input from the user and creates an Email to be sent off to a distro list. I am having an issue with getting the date from the form to convert nicely to a different format. The current output shows and "YYYY-MM-DDTHH:MM" and I am looking to have it show "MM/DD/YYYY H:MM AM/PM"
Here is the line of Codes in HTML
<body>
<div class="row">
<div class="cell">Event Start:</div>
<div class="cell">
<div class="cell"><input type="datetime-local" id="start_dt" /></div>
</div>
</div>
<div class="row">
<div class="cell"> </div>
<div class="cell" style="text-align: center;"><button type="submit" style="width: 90%;" class="SubmitButton" onClick="createEmail();">Generate Email</button></div>
</div>
<script src="JS\testemail.js"></script>
</body>
And hers is my JavaScript
function createEmail() {
let f = document.getElementById("start_dt").value.replace("T", " ");
let m_to = "Distro_List"
let m_cc = "CC_List"
document.location.href = "mailto:" + encodeURIComponent(m_to) + "?cc=" + encodeURIComponent(m_cc)
+ " &subject=Storm Mode"
+ " "
+ "&body="
+ "%0D%0A%0D%0A"
+ "Event Start: " + encodeURIComponent(f) + "%0D%0A"
}
I have tried a few of the solutions found on SO using Librarys with momement.js, but I can not download this onto my work machine. Here is the solution from SO that I tried to implement How to format a JavaScript date
and I tried using this site https://www.valentinog.com/blog/datetime/
I know my lack of knowledge on HTML and JS has me stumped on what I should do next. Any direction or pointers to help me on my way will be greatly appreciated.
Sorry for the messy code, I am still learning
|
be434bced3422521a47a4051f911dcabd5d5405ded24d43553d69cc4cf97245c | ['94d8ffa78dac421ab8ec4de7f6848f0a'] | As <PERSON> pointed out i had to let the images load first but that was not enough
I also had to change it to this format:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
all_of_the_async_logic(request,sendResponse);
return true;
});
that way i could tell the connection to wait for response (using return true and dropping the async in the listener)
| 9cb16ef3a2d726a27d4285e45dfe07e8eae4d56b5fd658621dd3f270e12b197e | ['94d8ffa78dac421ab8ec4de7f6848f0a'] | wOxxOm said the answer:
The thing is, content scripts can't make cross-origin requests in new
Chrome so you'll have to use an extension page. For example you can
add an iframe to the web page, pointing to an html file inside your
extension directory exposed via web_accessible_resources. That iframe
will have a chrome-extension:// URL and will be able to make
cross-origin requests for URLs listed in permissions
|
57cd63221cf41f0209e271acbc1c3d86f6fd3f563f109ad14b57601becfe8d7c | ['94dbf82b62ae45e68dcd58f1c6cb2561'] | I have a file with abc.txt
abc.txt
hhjj
myhome _ dfdfdsfds
fdsfds
dfdfdsfdsd
fdsfdsf
dfdfdsfdsdfdsfd
dfdsfds
dfdsfds
_
hhhh
jjj
kkkk
The character after myhome could be any character it could be special characters,letters or numbers.I need to find the character after myhome and delete the lines in between and that end with character. In my file I have mentioned as '' after myhome and with ''.
The output should be
abc.txt
hhjj
hhhh
jjj
kkkk
I have tried how to read a file by line by line
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileLineByLine {
public static void main(String[] args) {
try {
File file = new File("abc.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Could anyone help ??
| e20b8197a920b7a7cdc90fdf7e3ac6c37bf8d973df498c8d118b1411346c7f0e | ['94dbf82b62ae45e68dcd58f1c6cb2561'] | I am implementing the IPv6 support in Java using the "java-ipv6-0.17" jar ?
I have got the start range and end range using the code below but I need all the IP's in the given subnet ?
import com.googlecode.ipv6.IPv6NetworkMask;
public class IP {
public static void main(String[] args) {
final IPv6Network strangeNetwork = IPv6Network.fromString("2001:0db8::/31");
System.out.println("Start Range:"+ " "+ strangeNetwork.getFirst());
System.out.println("End Range:"+ " "+ strangeNetwork.getLast() + "\n");
Output :
Start Range: 2001:db8::
End Range: <IP_ADDRESS><IP_ADDRESS>/31");
System.out.println("Start Range:"+ " "+ strangeNetwork.getFirst());
System.out.println("End Range:"+ " "+ strangeNetwork.getLast() + "\n");
Output :
Start Range: 2001:db8<IP_ADDRESS>
End Range: 2001:db9:ffff:ffff:ffff:ffff:ffff:ffff
Could anyone please help and provide the code snippet ?
|
33fe86984ff3208f4ac53bf5363339db8b003f076889c8edab1c28787c1710b7 | ['94ddf8e8f5b2426082b32e0bdbb12ee1'] | Unfortunately, as announced on November 17, 2020 (https://developer.microsoft.com/graph/blogs/outlook-rest-api-v2-0-deprecation-notice/) version 2.0 of the Outlook REST API has been deprecated and will be fully decommissioned in November 2022.
They recommend Microsoft Graph API instead, see https://learn.microsoft.com/en-us/outlook/rest/compare-graph
| 606cf3f9257ec996e7753ce94ef38f8f591839b24784fbc0984d75983ffd2cb9 | ['94ddf8e8f5b2426082b32e0bdbb12ee1'] | I'm in search for a solution to the same issue. Unfortunately I don't think one is available.
In mature document-based DBs (such as MongoDB) you should be able to specify a queried index (see https://docs.mongodb.org/manual/reference/operator/update/positional/#up.S), but DynamoDB doesn't support that.
The next best thing is to query the Cart document with the entire CartItems array, iterate it to find the index of your CartItem and do a conditional write. (For example: update the document and set CartItems[7].Quantity to 4 only if CartItems[7].ProductId is "WSK-1234")
Yes you need to do a read before a write and perform some client-side searching, but at least you can be sure you aren't updating the wrong item.
|
490932233d0163a1ee1dcac59a04d5a5458e18c60cf75faa6252237a46ee1509 | ['94e3e1c54d354e3ebc0f9b52baa9e656'] | I am new to Power BI Desktop. I have integrated one data table into a dashboard and then created a dropdown list containing firm names from the table. I am wanting to be able to select multiple firm names at the same time which then populates separate summary tables for the firms that I had selected. Is that possible and how best could I do that? At the moment when I select 5 firm names all of the 5 summary tables show the same stats.
Many Thanks
<PERSON>
| dc4844379610a925e219c4cda8eb974701e42e86978d0747ac54efc7ee669069 | ['94e3e1c54d354e3ebc0f9b52baa9e656'] | I am quite new to using Selenium (Python). I have just scraped some data off a website in exactly the way I wanted to but the code only pulls off the first 10 records. It doesn't proceed to pick up the entire content by looping through the other pages. Would you happen to know why the script fails to open the proceeding pages? Any help would be greatly appreciated. If you find the """This is for navigation to next page""" I think this is the incorrect area.
Code:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchWindowException
import time
from openpyxl import Workbook
"""This is to collect links that associate with all the profiles present in Allen Overy website"""
def get_links(driver, target, upper_datetime_str, lower_datetime_str):
"""This part allows me to filter on date so I'm not having to pull back all the data each time it's run"""
if upper_datetime_str == '' and lower_datetime_str == '':
time_constrain = 0
else:
time_constrain = 1
upper_datetime = time.strptime(upper_datetime_str,'%d/%m/%Y')
lower_datetime = time.strptime(lower_datetime_str,'%d/%m/%Y')
"""This is to search for news that present in Freshfields website"""
"""Go to page that contains news list"""
driver.get(target)
isbreak = 0
list_links = []
while True:
try:
"""Get links that associate to news in each page"""
list_ppl_link = driver.find_elements_by_xpath('//div[@class = "srch-Title3"]')
for item in list_ppl_link:
rel_date = item.find_elements_by_xpath('//div[@class = "srch-Metadata2"]')
if time_constrain == 0:
rel_link = item.find_element_by_tag_name('a').get_attribute('href')
list_links.append(rel_link)
else:
input_datetime = time.strptime(rel_date,'%d %B %Y')
if input_datetime < lower_datetime:
isbreak = 1
break
elif input_datetime >=lower_datetime and input_datetime <= upper_datetime:
rel_link = item.find_element_by_tag_name('a').get_attribute('href')
list_links.append(rel_link)
"""This is for navigation to next page"""
next_b = driver.find_element_by_xpath('//div[@class="srch-Page srch-Page-bg"]')
if next_b.get_attribute('class') == 'srch-Page-img':
next_b.click()
else:
break
if isbreak == 1:
break
except KeyboardInterrupt:
break
except NoSuchWindowException:
break
except:
raise
return list_links
def get_news_content(driver, link):
driver.get(link)
try:
rels_date = driver.find_element_by_class_name('ao-rteElement-H4').text
except NoSuchElementException:
rels_date = ''
try:
headline = driver.find_element_by_class_name('ao-rteElement-H1').text
except:
headline = ''
try:
content1 = driver.find_element_by_class_name('ao-rteElement-introText').text
except NoSuchElementException:
content1 = ''
try:
content2 = driver.find_element_by_id('ctl00_PlaceHolderMain_main__ControlWrapper_ExtendedRichHtmlField').text
except NoSuchElementException:
content2 = ''
content = '\n'.join([content1, content2]).strip()
return {'news_date':rels_date ,\
'news_content':content, 'news_headline':headline}
def extract_data(adict):
return [adict.get('news_date', ''),
adict.get('news_headline', ''),
adict.get('news_content', '')]
===============================================================================================================
if name == "main":
"""Highlight the file variables such as file name and headers for columns with a date stamp of==="""
printout = time.strftime('%y%m%d_%H%M%S', time.localtime()) + '_allenovery_news.xlsx'
header = ['Firm Name','Date', 'Headline Title', 'News Content']
wb = Workbook()
ws = wb.active
ws.append(header)
log = open('test.txt', 'w')
"""Identify target link where the data is stored"""
target = 'http://www.allenovery.com/search/Pages/results.aspx?k=*&v1=-write&s=NewsAndDeals&r=aolanguage%3d%22AQdFbmdsaXNoCmFvbGFuZ3VhZ2UBAV4BJA%3d%3d%22'
"""Engage Chrome Driver"""
chromeOptions = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images":2}
chromeOptions.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)
driver.set_page_load_timeout = 120
driver.maximize_window()
"""Time format : dd/mm/yyyy"""
"""Select your timeframe below should you wish. Otherwise leave fields blank '' """
upper_datetime_str = ''
lower_datetime_str = ''
print('Collecting news links')
list_ppls = get_links(driver, target, upper_datetime_str, lower_datetime_str)
driver.quit()
"""Engage Chrome Driver"""
driver = webdriver.Chrome(chrome_options=chromeOptions)
driver.set_page_load_timeout = 120
driver.maximize_window()
total_link = len(list_ppls)
idx = 0
while idx < total_link:
try:
print(idx + 1, 'in', total_link, list_ppls[idx])
"""Append client name to data"""
ws.append(['Allen and Overy'] + extract_data(get_news_content(driver, list_ppls[idx])))
idx += 1
if not(idx%100):
wb.save(printout)
driver.quit()
time.sleep(10)
driver = webdriver.Chrome(chrome_options=chromeOptions)
driver.set_page_load_timeout = 120
driver.maximize_window()
except KeyboardInterrupt:
break
except NoSuchWindowException:
break
except:
driver.quit()
time.sleep(10)
driver = webdriver.Chrome(chrome_options=chromeOptions)
driver.set_page_load_timeout = 120
driver.maximize_window()
continue
wb.save(printout)
log.close()
driver.quit()
|
d764fa5550e346353e1358356a248dd021e31e3cbfc8bd2d1f38b7649f4ccd26 | ['94e74db33f4342e39aa53001f8a70250'] | I have written a java web application(deployed on glassfish server) to deploy on to Tomcat server. I copied the project file along with build.xml to a linux system and tried
[packwolf src]$ ant
Buildfile: build.xml
BUILD FAILED
/home/packwolf/Application/src/build.xml:12: The following error occurred while executing this line:
/home/packwolf/Application/src/nbproject/build-impl.xml:22: Class org.apache.tools.ant.taskdefs.condition.Not doesn't support the nested "antversion" element.
The web application is supposed to be portable, but it isn't. Any ideas to fix this?
| cc54f9ff35dd7d07ce72263a6ebf6a00facd76a804062fbb1be7a380bf00ec00 | ['94e74db33f4342e39aa53001f8a70250'] | I have 2 large integer arrays. I have to get the difference of these arrays(i.e. elements in 2nd array, not in 1st or vice versa). I am implementing a linear search and storing the difference in an array. Is there any way I can do it faster (Linear time)?
|
bd36fd8fcc4c5f3fe3e893d684a557b62748da8f1e5aa012a47c30a29eac995d | ['94f1ae171ab645d0951abc6dcd3f9514'] | Ive got a little difficult questions for me as a beginner.
I want to create an Android Layout:
My App does calculate how much rows and colums I need of several Textviews.
These need to be identified and the text in it needs to be renewed out of a database. Also, if the user touches one of the Textvies, it should take him to another Activity, but he needs to know exactly which of these Textviews he has clicked on.
I have tried to use several listviews, but it wasn't possible for me to identifie the created Textviews in it and make something by the identified data, when they are clicked.
New ideas to do it are really appreciated!
| 47bb62386b8a4bdffb611634b648dd40ffa6c0400111c25d22d80bba86c288b3 | ['94f1ae171ab645d0951abc6dcd3f9514'] | I need to parse a custom .json file like this:
{"04 Device Name " :
{
"ECU_1":
{
"01 Diagnostic" : "OK",
"02 CAN Id" : "123456789"
,
"01 SoftwareVersion " : {
"01 DID" : "123456789",
"02 Value " : "123456789"
}
,
"02 HardwareVersion " : {
"01 DID" : "123456789",
"02 Value " : "123456789"
}
}
}
into a custom .xml like this
<Component>
<ECUShortName>ECU_1</ECUShortName>
<LocationShortName>ECU_1_1</LocationShortName>
<LocationAccessKey>[Protocol]UDS_CAN_D.[EcuBaseVariant]BC_F213.[EcuVariant]123456789</LocationAccessKey>
<DiagnosticInfo>
<DiagnosticInfoValue>123456789</DiagnosticInfoValue>
</DiagnosticInfo>
<CommunicationProtocol>UDS</CommunicationProtocol>
<CommunicationState>8</CommunicationState>
<DTCCount>
<DTCCountValue>4</DTCCountValue>
</DTCCount>
<SWHWInformation>
<Software>
<PartNumber>
<PartNumberValue>123456789</PartNumberValue>
</PartNumber>
<Version>
<VersionValue>17/38/00</VersionValue>
</Version>
<Category>2</Category>
<Supplier>
<Code>1234</Code>
<Name>Supplier_1</Name>
</Supplier>
</Software>
<Hardware>
<PartNumber>
<PartNumberValue>123456789</PartNumberValue>
</PartNumber>
<Version>
<VersionValue>15/44/01</VersionValue>
</Version>
<Supplier>
<Code>1234</Code>
<Name>Supplier_1</Name>
</Supplier>
</Hardware>
</SWHWInformation>
I could use almost any language, but cant think of one that suits best.
VisualBasic would be good for XML, JS for JSON.
But it isn't correctly formatted in JSON...
Do you have any idea, how this could be done?
|
9b34a5aded747e9a080e273d16885a2fe90b645bcd275e25dcca6948b513c17f | ['94f81775c0cc46809d381a9547304144'] | So here is my code. I have to replace a space with an asterisk and if there are an occurence of two spaces in a row in the string replace it with one dash
<?php
$string = "Keep your spacing perfect!";
$search = array(' ',' ');
$search2 = array('*','-');
echo str_replace($search, $search2, $string);
?>
when i run it it prints out
Keep*your****spacing***perfect!
which is suppose to be
Keep*your--spacing-*perfect!
so what is wrong with my code and how do i fix it? I did some research but could not come to a solution. Any help is appreciated!
| 7b057cc427d350551de237c03e0783260cf99c49232c16d1bb47787308222bc5 | ['94f81775c0cc46809d381a9547304144'] | New to CSS . I am experiencing a problem where i only want to change elements within a class only. I have looked online and tried many ways but i really dont know whats the problem.
Here is the html part:
<nav class = "choice">
<ul>
<li><a href="#">Sign-in</a></li>
<li> | </li>
<li><a href="register.html">Register</a></li>
<li> | </li>
<li><a href="request.html">Request</a></li>
</ul>
</nav>
<footer class = "footer">
<h2>Site Map</h2>
<ul>
<li><a href="#">Home</a></li>
<li><a href="register.html">Register</a></li>
<li><a class = "active" href="about.html">How it All Works</a></li>
<section id = "copy">
<p>© 2018. All Rights Reserved.</p>
</section>
</ul>
</footer>
Here is the css:
.choice{
text-align : right;
}
ul {
list-style-type: none;
margin: 0;
padding: 1em;
width: 200px;
color:white;
}
li a {
display: block;
color: #00ff00;
padding: 8px 16px;
text-decoration: none;
}
li a.active {
background-color: #4CAF50;
color: white;
}
li a:hover:not(.active) {
background-color: #555;
color: white;
}
#copy{
position: absolute;
width: 100%;
color: #fff;
line-height: 40px;
font-size: 1em;
text-align: center;
bottom:0;
}
So long story short. I just want to change the elements "li" and "ul" under the class choice only but because i have same elements in the footer part, the selectors for the footer part will also change the elements in the class choice. What is the correct way to change g a specific part of a element only for that class ? Thank you
|
8a1191ab50ea417a847a77ec5b324343d26ed49d041411069d7bb6337e61386d | ['94ff672c9fc24122b4190e9ef566ab2a'] | I am trying to run the generateChangeLog to get the current structure of the database schema. However,i see that liquibase always returns empty file.
$ liquibase --logLevel=debug --driver=oracle.jdbc.OracleDriver --classpath="C:\temp\ojdbc8.jar" --changeLogFile="C:\db-changelog.xml" --url="jdbc:oracle:thin:@localhost:1521:xe" --username=system --password=oracle --defaultSchemaName=system generateChangeLog
Starting Liquibase at Tue, 23 Oct 2018 14:16:42 IST (version 3.6.2 built at 2018-07-03 11:28:09)
Liquibase command 'generateChangeLog' was executed successfully.
Also, though i have specified the loglevel as debug, i dont see liquibase generating logs .
Any help is appreciated.
Thanks
| 544076b12d7ab400836ccecc70c0254934809c73a448a24904fbd288f60a2730 | ['94ff672c9fc24122b4190e9ef566ab2a'] | I am trying to parse an Simple XMl file read from disk and convert that to JSON and store it back to a file using Mulesoft.
This is how the mule flow.xml looks like
<file:connector name="File" autoDelete="false" streaming="true" validateConnections="true" doc:name="File"/>
<file:connector name="File1" outputPattern="sample1.txt" autoDelete="false" streaming="true" validateConnections="true" doc:name="File"/>
<flow name="datatranformerFlow">
<file:inbound-endpoint path="C:\Madhu" name="sample.xml" responseTimeout="10000" doc:name="File" connector-ref="File"/>
<file:file-to-string-transformer mimeType="application/xml" doc:name="File to String"/>
<splitter expression="#[xpath3('/Names/Name')]" doc:name="Splitter"/>
<json:xml-to-json-transformer doc:name="XML to JSON"/>
<file:outbound-endpoint path="C:\Madhu\GV dev documents\WD files" connector-ref="File1" responseTimeout="10000" doc:name="File"/>
</flow>
The sample xml file that i am trying to parse looks like
<Names>
<Name>
<title>bnbnbha</title>
<firstname>aa</firstname>
<lastname>aaa</lastname>
</Name>
<Name>
<title>bjkjkjk</title>
<firstname>bb</firstname>
<lastname>bbb</lastname>
</Name>
<Name>
<title>hjhjhc</title>
<firstname>cc</firstname>
<lastname>ccc</lastname>
</Name>
<Name>
<title>djkjkj</title>
<firstname>dd</firstname>
<lastname>ddd</lastname>
</Name>
</Names>
When i run the mule project, i am getting an exception
INFO 2016-07-29 11:56:25,287 [[datatranformer].File.receiver.01] org.mule.transport.file.FileMessageReceiver: Lock obtained on file: C:\Madhu\sample.xml
INFO 2016-07-29 11:56:26,193 [[datatranformer].datatranformerFlow.stage1.02] org.mule.routing.ExpressionSplitter: The expression does not evaluate to a type that can be split: java.lang.String
ERROR: 'Unexpected character 'b' (code 98) in prolog; expected '<'
at [row,col {unknown-source}]: [2,3]'
ERROR 2016-07-29 11:56:26,272 [[datatranformer].datatranformerFlow.stage1.02] org.mule.exception.DefaultMessagingExceptionStrategy:
Message : com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character 'b' (code 98) in prolog; expected '<'
at [row,col {unknown-source}]: [2,3] (javax.xml.transform.TransformerException)
Payload :
bnbnbha
aa
aaa
Is there something i am doing wrong ?
|
c8430292df9e1d24d9d1bc08fcda9a7148757026ca8a04e4869599f59b91df83 | ['94ff8b861f434f4fa4a7201dca4d84f2'] | I am building a user flask application using MySQL and in the user login code i get the error TypeError: string indices must be integers every time.
@app.route('/signin',methods=['GET','POST'])
def signin():
if request.method == 'POST':
email = request.method['email']
password_entered = request.method['password']
cur = mysql.connection.cursor()
user = cur.execute("SELECT * FROM users WHERE email = %s",(email))
if user > 0:
data = cur.fetchone()
real_password = data['password']
name = data['name']
email = data['email']
if pbkdf2_sha256.verify(password_entered,real_password):
session['logged_in'] = True
session['name'] = name
session['email'] = email
flash('Sign In Successful!',category='info')
return redirect(url_for('index'))
else:
flash('Details Incorrect!Please try again.',category='error')
return render_template('signin.html')
else:
flash('User does not exist!Please Register.',category='error')
return redirect(url_for('signup'))
return render_template('signin.html')
Python shows that the error is from the line email = request.method['email']. Please assist.
| 73b84431ed76294bd3b8fa7ec83b86aa182ac7d237549d4a2a22f877b5a9947c | ['94ff8b861f434f4fa4a7201dca4d84f2'] | I have been trying to display data from MySQL db but nothing is working. Here is the code:
@app.route('/',methods=['GET','POST'])
def index():
if request.method == "POST":
food = request.form['food']
cur = mysql.connection.cursor()
data = cur.execute("SELECT * FROM recipies WHERE title = %s",[food])
if data > 0 :
results = cur.fetchall()
return render_template('results.html',results=results)
and the html
% extends "base.html" %}
{% block content %}
{% for result in results %}
<table>
<td>{{ result }}</td>
</table>
{% endfor %}
{% endblock %}
When i run it,it gives an error "TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement."
I don't know what to do.
|
cd9d050c273b9b5851f876d32a7e583ce5d59d4c78dc5589476832b36cb42789 | ['9524bb3da7c34f53bc11063c62c3a827'] | Problem:
I'm currently parsing a time series dataset, of [x,y] coordinates. The data isn't complete - it contains gaps and jitter, and I would like to fill these gaps / normalise the jitter using statistical analysis.
Background:
I'm currently reading up on non-linear regression (specifically polynomial regression -> PR) - which seems to be the best fit (pun intended) for my problem.
I realise that PR deals with arcs "turning in one direction" so, I'm going to try to refactor my code to work with smaller sample sizes - and work my way along the time series.
Questions:
Am I on the right track?
Is there a name for what I'm trying to do? i.e. using polynomial regression across an ongoing graph (curve fitting? trendline? continuous regression?)
Is there another technique I can/should use, that provides a better "fit" for my data?
| f0aad0750c02afaffd163c86503271f089d5023f3b745b5e5613a0421037178e | ['9524bb3da7c34f53bc11063c62c3a827'] | You'll do ok. But you might be a little bored as your cohort will be unorganized students fresh from high school who are in the process of growing up. You have all the skills in self motivation, you're engaged with the subject and interested, you'll actually do the assignments and with covid you won't spend all your time in the pub. |
80813d1e8166ae4f1f1150c91f83f692fdbe6dfad2e5da635c443e2febf52bc9 | ['9524ea873cf7427ebcde067be0369c5c'] | You could perhaps, ask the user to select the file that you are wanting to select using the File Dialog Box.
Option Explicit
Public Enum FileDialogType
msoFileDialogOpen = 1
msoFileDialogSaveAs = 2
msoFileDialogFilePicker = 3
msoFileDialogFolderPicker = 4
End Enum
Public Function OpenTargetWBExample()
Dim FilePath As String: FilePath = FileDialog(msoFileDialogFilePicker, "Select workbook to open")
If Len(FilePath) = 0 Then Exit Function
Dim TargetWB As Workbook: Set TargetWB = Workbooks.Open(FilePath)
'Extra code goes here
Set TargetWB = Nothing
End Function
Public Function FileDialog(ByVal DialogType As FileDialogType, Optional ByVal DialogTitle As String, _
Optional MultiSelect As Boolean, Optional ByVal FileFilter As String) As String
'If MultiSelect then outputs files in the following format: "File1;File2;File3"
'Custom File Extension Filter Format: "File Description 1~File Extension Filter 1|File Description 2~File Extension Filter 2"
Dim FileDialogObject As FileDialog: Set FileDialogObject = Application.FileDialog(DialogType)
Dim Index As Long, Filters() As String, Element() As String
Dim SelectedFile As Variant
With FileDialogObject
If Len(DialogTitle) > 0 Then .Title = DialogTitle
.AllowMultiSelect = MultiSelect
If Len(FileFilter) > 0 Then
Filters = Split(FileFilter, "|")
For Index = 0 To UBound(Filters)
Element = Split(Filters(Index), "~")
.Filters.Add Element(0), Element(1), (.Filters.Count + 1)
Next Index
End If
.FilterIndex = 0
.Show
.Filters.Clear
For Each SelectedFile In .SelectedItems
FileDialog = FileDialog & CStr(SelectedFile) & ";"
Next SelectedFile
If Len(FileDialog) > 0 Then FileDialog = Left(FileDialog, Len(FileDialog) - 1)
End With
Set FileDialogObject = Nothing
End Function
| 7400efb63ba246096977311b7301b674d5ca014b216b86c7347d6ce745f8c844 | ['9524ea873cf7427ebcde067be0369c5c'] | Insert the following into your Sheet1 (Sheet1) VBA module (Or the module that pertains to the worksheet you want this functionality in)
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Column = 1 Then Rows(Target.Row + 1).EntireRow.Insert
Application.EnableEvents = True
End Sub
This inserts a row below the changed cell if that cell's column number is column 1 or A
|
3530002dedfda441a71074929c5b2f128dde6850daf79d3902c9ffc8e3589607 | ['952b0f1e5ced4471b4731c2b1a88aa69'] | I tried this code and get succeed.
//backend option for price
$value= get_option('price');
// the query
$args = array ('meta_query' => array(
array( 'key' => '_price',
'value' => $value,
'compare' => '>=',
'type' => 'NUMERIC',
),
),
'post_type' => 'product',
);
// The Query
$query = new WP_Query( $args ); ?>
<?php if ( $query->have_posts() ) : ?>
<!-- the loop -->
<?php $stack = array();?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php $a = $product->get_categories(); ?>
<?php if (!in_array($a, $stack)) : ?>
<li class="product-category">
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ){
$category_name = $term->name;
$category_id = $term->term_id;
$category_slug = $term->slug;
$category_thumbnail = get_woocommerce_term_meta($term->term_id, 'thumbnail_id', true);
$image = wp_get_attachment_url($category_thumbnail);
echo '<img class="absolute category-image" src="'.$image.'">';
}
echo '<a href="' . get_term_link( $category_slug, 'product_cat' ) . '?min_price='.$value.'&max_price=1000500' . '">' . $category_name . '</a>';
?>
| 6ce4a1e288faffac1a6cf03b3081f8ad9cb44923e7143767691ebdd26ab10893 | ['952b0f1e5ced4471b4731c2b1a88aa69'] | I want to show product variations which come through the woo-commerce gravity form add-ons
on the cart page in the table after product name column.
Mean I want to show the product options which can change or update after adding to the cart.
How can I do ?
Please help me out to sholve the problem.
Thanks
|
2eb29f4bb67dd7ef36cff249e147af6454aca5f41e63eded38bb67db9f8fefbb | ['952c52040c754ce98169fe2433569f89'] | I'm currently working on a web app that is deployed to a server on our (company) domain. We're looking to migrate to Azure. Migrating our whole AD to Azure is out of our scope at the moment.
Now, my question is: Is there a way to acess on-premises Active Directory or Office 365 from my app deployed to Azure?
| 874675ef4ae100b5889a6735c62ecf30f21a9c3ef6e4d7f2a53a6460f5ec7c80 | ['952c52040c754ce98169fe2433569f89'] | I am trying to create a query from Flash Builder to PHP/mySQL with selectedItems. I have a simple SELECT query set up to populate a datagrid of items I would like to select for main query (two records looks something like this "19 10","20 10"). This is where I get stuck. I don't know if I need to break down the selectedItems in Flash Builder for formatting in SQL or if I can do it in PHP.
I would assume that it should be done in Flash Builder and I would then send the partial SQL statement to PHP.
As of right now, Flash Builder is holding the selected values as CustomObjects and I unsure of how to retrieve what is in the objects for formatting.
var arr:Array = dataGrid.SelectedItems
This yields an array of CustomObjets and I lost from there.
I will need the resulting SQL statement would need to look something like this.
SELECT *
FROM Stats
WHERE neu IN ('19 10','20 10');
Thank you for your help in advance.
|
9f3a914e7207d8d4f6e56db8ffb2e55a880336317e9ef2257b3cfb92d6e41056 | ['952f995b7d284c6082ed2c658caad765'] | I think I found a simpler solution to this question that just involves Bootstrap and JQuery.
See http://jsfiddle.net/key2xanadu/zfsfz0c9/.
The solution involves ID tagging the puppies and then tooltipping them at the bottom:
$('document').ready(function () {
$("#text_title").tooltip({placement: 'bottom', title:"HELLO TITLE!"});
$("#label_one").tooltip({placement: 'bottom', title:"HELLO ONE!"});
$("#label_two").tooltip({placement: 'bottom', title:"HELLO TWO!"});
});
Example also shows how to add tooltips to the title!
| 18df4db2433ea6581cd3e972ca7e743a49c02ae60bfa6062f31303dbfaa785cd | ['952f995b7d284c6082ed2c658caad765'] | I've been playing around with the Google Glass Mirror API and want to be able to stream a video.
This is the Python code snippet I tried:
def _insert_item_video_stream(self):
"""Insert a timeline item with streaming video."""
logging.info('Inserting timeline item with streaming video')
body = {
'notification': {'level': 'DEFAULT'},
'menuItems' : [{'action' : 'PLAY_VIDEO'},
{'payload' : 'https://eye-of-the-hawk.appspot.com/static/videos/waterfall.mp4'}],
}
self.mirror_service.timeline().insert(body=body).execute()
return 'A timeline item with streaming video has been inserted.'
However, the video was just blank. Any ideas would be super helpful!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.