id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_3200
|
When I stop the server, all the unanswered responses show up in the browser console:
POST http://localhost:3000/action/searchTextIndex net::ERR_EMPTY_RESPONSE
POST http://localhost:3000/action/searchTextIndex net::ERR_EMPTY_RESPONSE
POST http://localhost:3000/action/searchTextIndex net::ERR_EMPTY_RESPONSE
Here is my AJAX call. NOTE: this is throttled to call at an 800ms max frequency.
search(query, dbCollection) {
axios.post('/action/searchTextIndex', {
dbCollection,
query
})
.then(response => {
console.log(response);
})
.catch(err => console.log(err))
}
And here is the express js code:
const searchTextIndex = (req, res, db) => {
const { query, collection } = req.body;
db.collection(collection).find(
{ $text: { $search: query } }
)
.project({ score: { $meta: 'textScore' } })
.sort({ score: { $meta: 'textScore' } })
.toArray((err, result) => {
if (err) {
console.log(err);
res.send({ type: 'server_error' });
return;
}
console.log(result);
return;
})
}
Why would it only work five times, even if I wait a few seconds before pressing each character in the search field?
A: It looks like the problem is that no response is sent for the happy path on your server. See if this works. If this doesn't fix it, include the code where the db parameter is defined and passed as an argument to searchTextIndex.
const searchTextIndex = (req, res, db) => {
const { query, collection } = req.body;
db.collection(collection).find(
{ $text: { $search: query } }
)
.project({ score: { $meta: 'textScore' } })
.sort({ score: { $meta: 'textScore' } })
.toArray((err, result) => {
if (err) {
console.log(err);
res.send({ type: 'server_error' });
return;
}
console.log(result);
// need to be sure you send the response
return res.json(result);
})
}
| |
doc_3201
|
i already created it but i want display a message box after click on Reload
i tried
#define MSG (WM_APP + 101)
HWND hWnd = FindWindow(NULL,TEXT("untitled - Notepad"));
HMENU hCurrent = GetMenu(hWnd);
HMENU hNew = CreateMenu();
AppendMenu(hCurrent, MF_STRING | MF_POPUP, (unsigned int)hNew, TEXT("TheDragoN"));
AppendMenu(hNew, MF_STRING, MSG, TEXT("Reload"));
AppendMenu(hNew, MF_STRING, 200, TEXT("Credits"));
DrawMenuBar(hWnd);
WPARAM wParam;
switch(LOWORD(wParam))
{
case MSG:
MessageBox(hWnd, L"TSSAA", L"MessSDSageBox",MB_OK);
break;
}
but it didnt display the message box
A: You declare WPARAM wParam; without any initialisation and immediatelly check what's in lo word, result is unspecified as wParam will contain some default rubbish value.
| |
doc_3202
|
This is being done within AWS EMR, so I don't think I'm putting these options in the correct place.
This is the command I want to send to the cluster as it spins up: spark-shell --packages com.databricks:spark-csv_2.10:1.4.0 --master yarn --driver-memory 4g --executor-memory 2g. I've tried putting this on a Spark step - is this correct?
If the cluster spun up without that being properly installed, how do I start up PySpark with that package? Is this correct: pyspark --packages com.databricks:spark-csv_2.10:1.4.0? I can't tell if it was installed properly or not. Not sure what functions to test
And in regards to actually using the package, is this correct for creating a parquet file:
df = sqlContext.read.format('com.databricks.spark.csv').options(header='false').load('s3n://bucketname/nation.tbl', schema = customSchema)
#is it this option1
df.write.parquet("s3n://bucketname/nation_parquet.parquet")
#or this option2
df.select('nation_id', 'name', 'some_int', 'comment').write.parquet('com.databricks.spark.csv').save('s3n://bucketname/nation_parquet.tbl')
I'm not able to find any recent (mid 2015 and later) documentation regarding writing a Parquet file.
Edit:
Okay, now I'm not sure if I'm creating my dataframe correctly. If I try to run some select queries on it and show the resultset, I don't get anything and instead some error. Here's what I tried running:
df = sqlContext.read.format('com.databricks.spark.csv').options(header='false').load('s3n://bucketname/nation.tbl', schema = customSchema)
df.registerTempTable("region2")
tcp_interactions = sqlContext.sql(""" SELECT nation_id, name, comment FROM region2 WHERE nation_id > 1 """)
tcp_interactions.show()
#get some weird Java error:
#Caused by: java.lang.NumberFormatException: For input string: "0|ALGERIA|0| haggle. carefully final deposits detect slyly agai|"
| |
doc_3203
|
Possible Duplicate:
Translating human languages in Python
I am trying to develop an application that can accept input from users and translate the input language to another language using python. I have tried to use the replace string function in python but it is not working. I also tried using the gettext module but I am not very sure it can do the job.
A: gettext is a quite standard way for translating messages, strings etc. which are a part of your software, but not for translating user input.
To translate user input it is better to use 3rd party services & APIs like Google Translate, Being Translator etc. Most of them have ready to run python interface. Some of them are paid services.
| |
doc_3204
|
The goal is to recreate the behavior of Stabilizer, but in a distributed environment with complex deployment. (As far as I can tell, that project is no longer maintained and never made it past a prototype phase.) In particular, the randomization should take place (repeatedly) at runtime and without needing to invoke the program through a special binary or debugger. On the other hand, I assume full access to source code and the ability to arbitrarily change/recompile the system under test.
By "complex deployment", I mean that there may be different binaries running on different machines, possibly written in different languages. Think Java programs calling into JNI libraries (or other languages using FFI), "main" binaries communicating with sidecar services, etc. The key in all of these cases is that the native code (the target of randomization) is not manually invoked, but is somehow embedded by another program.
I'm only concerned about the randomization aspect (i.e., assume that metrics collection/reporting is handled externally). It's fine if the solution is system-specific (e.g., only runs on Linux or with C++ libraries), but ideally it would be a general pattern that can be applied "anywhere", regardless of the compiler/toolchain/OS.
Side note: layout issues are less of a concern on larger systems thanks to the extra sources of random noise (network, CPU temperatures/throttling, IPC overheads, etc). However, in many cases, distributed applications are deployed on "identical" machines with uniform environments, so there's still plenty of room for correlated performance impacts. The goal is just to debias the process for decision making.
| |
doc_3205
|
View passes empty data to serializer.
views.py
class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView):
permission_classes = (IsAuthenticated,)
renderer_classes = (UserJSONRenderer,)
serializer_class = UserSerializer
def retrieve(self, request, *args, **kwargs):
serializer = self.serializer_class(request.user)
return Response(serializer.data, status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs):
serializer_data = request.data.get('user', {})
print(f'request data: {request.data}') # prints empty dic {}
serializer = self.serializer_class(
request.user, data=serializer_data, partial=True
)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
When I run PUT or PATCH request on Postman, I get unchanged user which is related to a token.
postman:
Postman
django terminal says:
Error
Can someone explain what am I doing wrong?
UPD:
I don't know why, but django can't receive '{' in PUT request.
I echoed in postman-echo.com/put.
It responded the same body I sent.
Echo of PUT request
How to make Django accept '{' at the beginning of a request body?
A: it happen to me as well, following a tutorial, so i replaced this:
serializer_data = request.data.get('user', {})
with just this:
serializer_data = request.data
seems to work (at least for me),hope that helps.
| |
doc_3206
|
1. Remove from the monitoring (Third party tool via API)
2. Delete the record set.
A: You want to use an Autoscaling Lifecycle Hook. Check out the documentation here.
| |
doc_3207
|
public class ItemControl : LinkLabel {}
public class ItemsControl : UserControl
{
private readonly List<ItemControl> items;
public TaskBox()
{
this.items = new List<ItemControl>();
}
public List<ItemControl> Items
{
get { return this.items; }
}
}
But how can I draw the items on the UserControl once I add them to the list? Also how can I add the clicked event to them in code?
A: You can put a FlowLayoutPanel control on your ItemsControl and use following code to draw ItemControls to it:
foreach (var item in this.Items)
{
flowLayoutPanel1.Controls.Add(item);
item.LinkClicked += item_LinkClicked;
}
void item_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
MessageBox.Show(((item)sender).Name);
}
Using FlowLayaoutPanel is arbitrary, but If you don't use FlowLayoutPanel, you can put each LinkItem directly on your UserControl, and have to manage each LinkItem location, yourself.
| |
doc_3208
|
Here is the action:
// get /application/index
public ActionResult Index(string application, object catchAll)
{
// forward to partial request to return partial view
ViewData["partialRequest"] = new PartialRequest(catchAll);
// this gets called in the view page and uses a partial request class to return a partial view
}
Example:
The Url "/Application/Accounts/LogOn" will then cause the Index action to pass "/Accounts/LogOn" into the PartialRequest, but as a string value.
// partial request constructor
public PartialRequest(object routeValues)
{
RouteValueDictionary = new RouteValueDictionary(routeValues);
}
In this case, the route value dictionary will not return any values for the routeData, whereas if I specify a route in the Index Action:
ViewData["partialRequest"] = new PartialRequest(new { controller = "accounts", action = "logon" });
It works, and the routeData values contains a "controller" key and an "action" key; whereas before, the keys are empty, and therefore the rest of the class wont work.
So my question is, how can I convert the "/Accounts/LogOn" in the catchAll to "new { controller = "accounts", action = "logon" }"??
If this is not clear, I will explain more! :)
Matt
This is the "closest" I have got, but it obviously wont work for complex routes:
// split values into array
var routeParts = catchAll.ToString().Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
// feels like a hack
catchAll = new
{
controller = routeParts[0],
action = routeParts[1]
};
A: You need to know what part is what in the catchAll parameter. Then you need to parse it yourself (like you are doing in your example or use a regexp). There is no way for the framework to know what part is the controller name and what is the action name and so on, as you haven't specified that in your route.
Why do you want to do something like this? There is probably a better way.
| |
doc_3209
|
A: A Set is a somewhat ordered (that's why it is Iterable) but not-sorted collection of elements.
If you want the elements to be sorted, you must use a SortedSet implementation (TreeSet), where you can provide the ordering when creating a new instance
Update: The difference between ordered and sorted is not really clear: You can say a List is ordered but may be not sorted and a Map is unordered and unsorted, but the implementation of a Map requires to keep its elements in memory (RAM, disk, whatever support you want) and that memory is always ordered, so it gives some order to any Collection (for example the insertion order or the storage order).
An example of this undefinition can be seen in the Scala API: When defining a SortedSet, the constructor is:
new TreeSet()(implicit ordering: Ordering[A])
So the word "ordering" is used instead of "sorting"
| |
doc_3210
|
So I have UITableView -> UITableViewCell and in my UITableViewCell have UICollectionView. It contains dishes
On the top, I also have cell with CollectionView with horisontal scroll. It contains categories
And I want to move categories when I Scroll dishes. I try to catch scroll event in UITableViewCell class(that contains collectionView)
extension ProductCollectionViewCell:UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate{
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
startScroll()
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
startScroll()
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startScroll()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == productsCollectionView && productsModel.count != 0 {
startScroll()
}
}
}
But nothing of this event was catched=( The doesn't call. It only calls on Controller with UiTableView. How can I make it?
A: So yes. As Ptit Xav Sad - it is inpossible to catch. I chenged all screen to collectionView
| |
doc_3211
|
I've posed a CSV file with some sample data here:
https://drive.google.com/open?id=0B4xdnV0LFZI1dzE5S29QSFhQSmM
We make cakes, and 99% of our cakes are made by us. The 1% is when we have a cake delivered to us from a subcontractor and we 'Receive' and 'Audit' it.
What I wanted to do was to write something like this:
SELECT
Cake.Cake
Instruction.Cake_Instruction_Key
Steps
FROM
Cake
Join Instruction
ON Cake.Cake_Key = Instruction.Cake_Key
JOIN Steps
ON Instruction.Step_Key = Steps.Step_Key
WHERE
MIN(Steps.Step_Key) = 1
This fails because you can't have an aggregate in the WHERE clause.
The desired results would be:
Cake C 13 Receive
Cake C 14 Audit
Cake D 15 Receive
Cake D 16 Audit
Thank you in advance for your help!
A: Take a look at the HAVING keyword:
https://msdn.microsoft.com/en-us/library/ms180199.aspx
It works more or less the same as the WHERE clause but for aggregate functions after the GROUP BY clause.
Beware however this can be slow. You should try filtering down the number of records as much as possible in the WHERE and even consider using a tempory table to aggregate the data into first.
A: What you're talking about is the GROUP BY/HAVING clause, so in your case you would need to add something like
GROUP BY Cake.Cake, Instruction.Cake_Instruction_Key, Steps
HAVING MIN(Steps.Step_Key) = 1
| |
doc_3212
|
There are given some errors displayed in the server:
1)There is no Action mapped for namespace /operators-in-java/operators-in-java/text and action name javascript. - [unknown location]
.........
2)There is no Action mapped for namespace /super-keyword/text and action name javascript. - [unknown location]
3)There is no Action mapped for namespace /operators-in-java/operators-in-java/history-and-features-of-java/text and action name javascript. - [unknown location]
etc.
I've performed global exception handling as given below:
<global-results>
<result name="excepHandler">/handler.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="excepHandler"/>
</global-exception-mappings>
But it doesn't handle, this type of error. Thanx in advance.
A: Probably the easiest way is to use wild cards. Simply make a action for "*" and have that direct to your error page. All actions with more specific names will override that case so it should be straight forward.
A: Does your clients get the 404, not found error?
You could configure your web.xml to redirect to an error page when somebody requests an invalid resource.
<error-page>
<error-code>404</error-code>
<location>/notFound.html</location>
</error-page>
But, I would try to fix whatever is causing the incorrect requests, instead of creating a catch all action. Apparently you've configured struts2 to handle every request, I would check on that first.
| |
doc_3213
|
I've got two dynamically generated tables. In this particular instance, one is 5 cells wide and 4 cells high, and the other table is 4 by 3.
There are:
*
*2 cells in the first table that belong to class "xyz";
*1 cell in the second table that belongs to class "xyz".
Table 1:
+----+----+----+----+----+
| |xyz | | | |
+----+----+----+----+----+
| | | | | |
+----+----+----+----+----+
| | | |xyz | |
+----+----+----+----+----+
| | | | | |
+----+----+----+----+----+
Table 2:
+----+----+----+----+
| | | |xyz |
+----+----+----+----+
| | | | |
+----+----+----+----+
| | | | |
+----+----+----+----+
What I can do is:
*
*get all "xyz" cells formatted with a particular border;
*get one "xyz" cell to update it's style on hover ( td.xyz:hover {...} ).
What I can't do is:
*
*get all cells belonging to "xyz" to update their style when hovering over one.
Is it possible to do this using only HTML and CSS?
A: No, CSS only works with sibling or child elements. Table cells in the same row are adjacent siblings, but cells in other rows others are not. Therefore you need to use JavaScript to accomplish this.
A: A jQuery solution would be:
$('.cellToHover').hover(function() {
$('.cellToHover').addClass('hovered');
}, function() {
$('.cellToHover').removeClass('hovered');
});
Here is a Fiddle.
| |
doc_3214
|
This is how I am connecting to the DB. I am using Visual Studio and C#.
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionNameHere"].ConnectionString))
{
sqlConn2.Open();
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS mWHERE table_name = 'registrants');
sqlCmd2.ExecuteNonQuery();
using (SqlDataReader sqlReader = sqlCmd2.ExecuteReader())
{
//Some code here?
}
sqlConn2.Close();
}
}
}
}
A: Avoid Web Forms and move to MVC if at all possible. If not, it is not the end of the world, but you are living in the dark ages. Also, never, ever, ever use inline SQL. Either switch to an ORM like EF or Insight.Database, or use stored procedures and parameterized ADO.NET calls.
Now that we have that out of the way.
It is simple really, you will need to do some reading to fully grasp how to bind your dataset or datatable to the web forms web controls. The datagrid is probably your best bet.
*
*https://msdn.microsoft.com/en-us/library/aa728895(v=vs.71).aspx
*http://www.c-sharpcorner.com/uploadfile/anjudidi/example-of-datagrid-in-Asp-Net/
Both of the links above detail the binding aspects and explain how to correctly use them. Again, if this can be avoided that it certainly what I would suggest.
Also, your ADO.NET calls will populate either a DataTable or a DataSet and then pass that to the Form for loading/binding.
using (SqlConnection sqlConn2 = new sqlConnection(ConfigurationManager.ConnectionStrings["ConnectionNameHere"].ConnectionString))
{
sqlConn2.Open();
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS mWHERE table_name = 'registrants');
var dataTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
sqlConn2.Close();
return dataTable;
}
}
A: ASP.NET Repeater Control is an ideal solution for your problem, you can simply define a template (for label & textbox in your case) and it will bind them accordingly.
Define a repeater control like this:-
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="lblTest" runat="server" Text='<%# Eval("MyColumn") %>'></asp:Label>
<asp:TextBox ID="textTest" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:Repeater>
Then, Change your query like this:-
DataTable table = new DataTable();
table.Columns.Add("MyColumn", typeof(string));
//Your rest code (connection object and all)
sqlCmd2.CommandText = "SELECT COLUMN_NAME AS MyColumn
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName";
sqlCmd2.Parameters.Add("@TableName",SqlDbType.NVarChar).Value = "registrants";
sqlConn2.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow tableRow = table.NewRow();
tableRow["MyColumn"] = reader["MyColumn"].ToString();
table.Rows.Add(tableRow);
}
Repeater1.DataSource = table;
Repeater1.DataBind();
}
Also, please note you should not use ExecuteNonQuery it is mainly used for DML operations. Using ExecuteReader will do the task.
| |
doc_3215
|
You define the url the resource connects to via the site= method. There should be an equivalent query_params= method or similar.
There is one good blog post I found related to this and it's from October 2008, so not exactly useful for Rails 3.
Update: I had a thought. Would a small Rack middleware or Metal be the answer to this? It could just pass through the request, tacking it's api_key on.
A: I have much nicer solution ! I try with Rack in middleware but i no find any solution in this way....
I propose you this module for override methods of ActiveReouse::Base
Add this lib in /lib/active_resource/extend/ directory don't forget uncomment
"config.autoload_paths += %W(#{config.root}/lib)" in config/application.rb
module ActiveResource #:nodoc:
module Extend
module AuthWithApi
module ClassMethods
def element_path_with_auth(*args)
element_path_without_auth(*args).concat("?auth_token=#{self.api_key}")
end
def new_element_path_with_auth(*args)
new_element_path_without_auth(*args).concat("?auth_token=#{self.api_key}")
end
def collection_path_with_auth(*args)
collection_path_without_auth(*args).concat("?auth_token=#{self.api_key}")
end
end
def self.included(base)
base.class_eval do
extend ClassMethods
class << self
alias_method_chain :element_path, :auth
alias_method_chain :new_element_path, :auth
alias_method_chain :collection_path, :auth
attr_accessor :api_key
end
end
end
end
end
end
in model
class Post < ActiveResource::Base
include ActiveResource::Extend::AuthWithApi
self.site = "http://application.localhost.com:3000/"
self.format = :json
self.api_key = 'jCxKPj8wJJdOnQJB8ERy'
schema do
string :title
string :content
end
end
A: Based on Joel Azemar's answer, but I had to make some changes..
First of all, in the active resource gem I used (2.3.8), there is no 'new_element_path', so aliasing that obviously failed..
Second, I updated the way the token is added to the query, because as was, it would break as soon as you add more params yourself. E.g. request for http://example.com/api/v1/clients.xml?vat=0123456789?token=xEIx6fBsxy6sKLJMPVM4 (notice ?token= i.o. &token=)
Here's my updated snippet auth_with_api.rb;
module ActiveResource #:nodoc:
module Extend
module AuthWithApi
module ClassMethods
def element_path_with_auth(id, prefix_options = {}, query_options = nil)
query_options.merge!({:token => self.api_key})
element_path_without_auth(id, prefix_options, query_options)
end
def collection_path_with_auth(prefix_options = {}, query_options = nil)
query_options.merge!({:token => self.api_key})
collection_path_without_auth(prefix_options, query_options)
end
end
def self.included(base)
base.class_eval do
extend ClassMethods
class << self
alias_method_chain :element_path, :auth
# alias_method_chain :new_element_path, :auth
alias_method_chain :collection_path, :auth
attr_accessor :api_key
end
end
end
end
end
end
A: Use model#prefix_options which is a hash for passing params into query string (or even as substitions for parts of the Model.prefix, e.g. "/myresource/:param/" will be replaced by the value of prefix_options[:param] . Any hash keys not found in the prefix will be added to the query string, which is what we want in your case).
class Model < ActiveResource::Base
class << self
attr_accessor :api_key
end
def save
prefix_options[:api_key] = self.class.api_key
super
end
end
Model.site = 'http://yoursite/'
Model.api_key = 'xyz123'
m = Model.new(:field_1 => 'value 1')
# hits http://yoursite:80/models.xml?api_key=xyz123
m.save
A: An Active Resource currently has no good way of passing an api key to the remote service. Passing api_key as a parameter will add it to the objects attributes on the remote service, I assume that this is not the behaviour you'd except. It certainly wasn't the behaviour I needed
A: I'd recommend that you have a base class inheriting from ActiveResource::Base and override the self.collection_path and self.element_path class methods to always inject the API KEY something like:
class Base < ActiveResource::Base
def self.collection_path(prefix_options = {}, query_options = {})
super(prefix_options, query_options.merge(api_key: THE_API_KEY))
end
def self.element_path(id, prefix_options = {}, query_options = {})
super(id, prefix_options, query_options.merge(api_key: THE_API_KEY))
end
end
class User < Base; end
User.all # GET /users/?api_key=THE_API_KEY
This will always inject your API_KEY in your ActiveResource method calls.
A: I recently was faced with a similar issue, if you are on Rails3, it supports using custom header which makes life much easier for these situations.
On the side you are making the request from, add
headers['app_key'] = 'Your_App_Key'
to the class you are inheriting from ActiveResource::Base
On you are server, for Authentication, simply receive it as
request.headers['HTTP_APP_KEY']
For Example:
class Magic < ActiveResource::Base
headers['app_key'] = 'Your_App_Key'
end
now Magic.get, Magic.find, Magic.post will all send the app_key
A: An Active Resource Object behaves much like a (simplified) Active Record object.
If you wish to pass through a new param, then you can set it on the AR object by adding it as an attribute. eg:
jane = Person.create(:first => 'Jane', :last => 'Doe', :api_key => THE_API_KEY)
it should pass the api_key as a parameter, along with all the others.
| |
doc_3216
|
So my questions is, can someone explain to me the following code snippet:
int i = 20;
int j = 25;
int k = (i > j) ? 10 : 5;
if (5 < j - k) {
//First expression
printf("the first expression is true.");
} else if ( j > i ) {
//Second Expression
printf("The second expression is true.");
} else {
printf("Neither expression is true.");
}
A: The int k = (i > j) ? 10 : 5; in your example is equivalent to:
if (i > j)
{
int k = 10;
}
else
{
int k = 5;
}
The ternary operator is just a shortcut for special cases of if-conditionals when assigning a value based on a condition.
The rest of the snippet is not that hard to understand, if remove the incomplete else if snippet:
if (5 < j(25) - k(5)) == if (5 < 20)
{
printf("the expression is true.");
}
else
{
printf("the expression is false.");
}
Because 5 is smaller than 25 - 5 = 20, This program will print "the first expression is true".
| |
doc_3217
|
$json = file_get_contents('abc.com/xyz');
file_put_contents('example.json', $json);
Like this an endpoint would be fetched and written into a local file. But to repeat this step continuously and keep the data updated this script would be needed to run permanently or executed frequently. The only way I found was to use cron jobs for that issue but would that be recommendable to use to keep files updated? Or are there way better methods to do this?
I know that there are better setups to solve that issue like handling it with node.js but I consider using a platform like this so I only have to manage the communication between the API and the server and not between server and clients and didn’t find another way to do so but I‘m open to other suggestions!
A: While it can be done differently (like with node.js you mentioned or other methods), I believe that a system cron job to be run every X minutes (depending on how long it takes for the API to respond) will suffice and keep things simple.
Provided of course that you are able to set-up system cron jobs on your webserver.
| |
doc_3218
|
procedure TForm1.Button1Click(Sender: TObject);
var
Form: TForm;
Brws: TWebBrowser;
begin
Form := TForm.Create(nil);
try
Form.Width := 500;
Form.Height := 500;
Form.BorderStyle := bsDialog;
Form.Position := poScreenCenter;
Form.Caption := 'Select the Option';
Brws := TWebBrowser.Create(Form);
Brws.ParentWindow := Form.Handle;
TWinControl(Brws).Parent := Form;
Brws.Align := alClient;
Brws.AddressBar := False;
Brws.MenuBar := False;
Brws.StatusBar := False;
Application.ProcessMessages;
if Form.ShowModal = mrOk then
Brws.Navigate('https://www.google.com');
finally
Form.Free;
end;
end;
The result is like WebBrowser is not responding. I got a white screen and no error messages.
Please, what am I missing? Thanks!
A: You are displaying the Form using its ShowModal() method, which is a synchronous (aka blocking) function that does not exit until the Form is closed. So, you are never reaching the call to Navigate() while the Form is open.
You have two options:
*
*Use Show() instead of ShowModal(). Show() signals the Form to display itself, and then exits immediately, allowing subsequent code to run while the Form is open. As such, you will have to get rid of the try...finally and instead use the Form's OnClose event to free the Form when it is closed, eg:
procedure TForm1.Button1Click(Sender: TObject);
var
Form: TForm;
Brws: TWebBrowser;
begin
Form := TForm.Create(Self);
Form.Width := 500;
Form.Height := 500;
Form.BorderStyle := bsDialog;
Form.Position := poScreenCenter;
Form.Caption := 'Select the Option';
Form.OnClose := BrowserFormClosed;
Brws := TWebBrowser.Create(Form);
TWinControl(Brws).Parent := Form;
Brws.Align := alClient;
Brws.AddressBar := False;
Brws.MenuBar := False;
Brws.StatusBar := False;
Form.Show;
Brws.Navigate('https://www.google.com');
end;
procedure TForm1.BrowserFormClosed(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
*
*Otherwise, if you want to keep using ShowModal() then move the call to Navigate() into the Form's OnShow or OnActivate event instead, eg:
procedure TForm1.Button1Click(Sender: TObject);
var
Form: TForm;
Brws: TWebBrowser;
begin
Form := TForm.Create(nil);
try
Form.Width := 500;
Form.Height := 500;
Form.BorderStyle := bsDialog;
Form.Position := poScreenCenter;
Form.Caption := 'Select the Option';
Form.OnShow := BrowserFormShown;
Brws := TWebBrowser.Create(Form);
TWinControl(Brws).Parent := Form;
Brws.Align := alClient;
Brws.AddressBar := False;
Brws.MenuBar := False;
Brws.StatusBar := False;
Form.ShowModal;
finally
Form.Free;
end;
end;
procedure TForm1.BrowserFormShown(Sender: TObject);
var
Form: TForm;
Brws: TWebBrowser;
begin
Form := TForm(Sender);
Brws := TWebBrowser(Form.Components[0]);
Brws.Navigate('https://www.google.com');
end;
| |
doc_3219
|
The script creates 1 d-word and 2 strings in HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\PersonalizationCSP
The d-word is LockScreenImageStatus
Strings are LockScreenImageUrl & LockScreenImagePath
Is there anyway to allow the users to still change the lock screen image after it has been set by this script?
| |
doc_3220
|
DECLARE @table NVARCHAR(50) = 'ToolList',
@val NVARCHAR(50) = 'test'
EXEC ('INSERT INTO ' + @table + 'SELECT ' + @val)
and
EXEC ('INSERT INTO ' + @table + '([col1]) VALUES(' + @val +')'
but still get an error that says
Incorrect syntax near 'test'.
A: you missed a space before SELECT and the @val should enclosed in single quote
DECLARE @table nvarchar(50) = 'ToolList',
@val nvarchar(50) = 'test'
EXEC ( 'INSERT INTO ' + @table + ' SELECT ''' + @val + '''')
when you use Dynamic SQL, it is easier to form the query in a variable so that you can print out , inspect the value before execution
select @sql = 'INSERT INTO ' + @table + ' SELECT ''' + @val + ''''
print @sql
exec (@sql)
A: You'd better use sp_executesql that allows for statements to be parameterized, to avoid the risk of SQL injection.
DECLARE @Query NVARCHAR(1000),
@table NVARCHAR(50) = 'ToolList'
SET @Query = 'INSERT INTO ' + @table + ' SELECT @val'
EXEC sp_executesql @Query, N'@val nvarchar(50)', @val = 'test'
sp-executesql-transact-sql
A: You can also use CHAR(39) instead of adding single quotes every time for better readability. And also, you have not added a space after the variable which contains the table name.
Query
declare @table nvarchar(50) = 'ToolList',
@val nvarchar(50) = 'test2';
declare @sql as varchar(max) = 'insert into ' + @table
+ ' select ' + char(39) + @val + char(39);
exec(@sql);
A: You need 4 singlequotes before the @val field as it is a string and all strings needs to be encapsulated in single quotes.
You can print the dynamic string using PRINT command check what the final string you are going to execute.
DECLARE @table VARCHAR(50) = 'ToolList'
DECLARE @val VARCHAR(50) = 'test'
DECLARE @DSQL AS VARCHAR(MAX) = ''
SET @DSQL = @DSQL + ' INSERT INTO [' + @table + ']' + '
SELECT ' + '''' + @val + ''''
--PRINT @DSQL
EXEC(@DSQL)
| |
doc_3221
|
<div class="message-text">Lorem ipsum http://google.com dolour sit
amet<br> </div>
I want click this http link and other all links.
How can I find it and make clickable via jQuery?
A: If I understand you right, you could use a normal hyperlink:
<div class="message-text">Lorem ipsum<a href="http://google.com">http://google.com</a> dolour sit amet<br> </div>
If for whatever reason that is not in option, you could try javascript:
<script type="text/javascript">
var a = document.createElement('a');
var linkText = document.createTextNode("Lorem ipsum http://google.com dolour sit
amet<br> ");
a.appendChild(http://google.com);
a.href = "http://google.com";
document.body.appendChild(a);
I hope this helps you at all!
A: In case you are trying to dynamically replace plain text URLs to clickable URLs (its HTML representation) there is a quite good discussion here
A: This isn't an exhaustive answer, but it may get you started. You have to take the text, turn it into a url then put it back. Here is how. And here is my fiddle.
$(function(){
var newStr;
var matchStr=$("div.message-text").html();
var REGEX_MATCHER_URL = LINK_DETECTION_REGEX = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?)(\s+|$)/gi
$("div.message-text").each(function(index, div){
var newDiv;
var oldDiv;
var oldTextArray;
var oldDivHtml = $(div).html();
$(div).html(""); // clear it
var matches = oldDivHtml.match(REGEX_MATCHER_URL);
$.each(matches, function(index, value){
var holder = oldDivHtml.split(value);
$(div).append(holder[0]);
$(div).append($("<a>").attr("href", value).html(value));
$(div).append(' ' + holder[1]);
});
});
});
| |
doc_3222
|
>>> x = dict(zip(range(0, 10), range(0)))
But that doesn't work since range(0) is not an iterable as I thought it would not be (but I tried anyways!)
So how do I go about it? If I do:
>>> x = dict(zip(range(0, 10), 0))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: zip argument #2 must support iteration
This doesn't work either. Any suggestions?
A: In python 3, You can use a dict comprehension.
>>> {i:0 for i in range(0,10)}
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
Fortunately, this has been backported in python 2.7 so that's also available there.
A: You need the dict.fromkeys method, which does exactly what you want.
From the docs:
fromkeys(...)
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
So what you need is:
>>> x = dict.fromkeys(range(0, 10), 0)
>>> x
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
A: PulpFiction gives the practical way to do it. But just for interest, you can make your solution work by using itertools.repeat for a repeating 0.
x = dict(zip(range(0, 10), itertools.repeat(0)))
A: You may want to consider using the defaultdict subclass from the standard library's collections module. By using it you may not even need to iterate though the iterable since keys associated with the specified default value will be created whenever you first access them.
In the sample code below I've inserted a gratuitous for loop to force a number of them to be created so the following print statement will have something to display.
from collections import defaultdict
dflt_dict = defaultdict(lambda:42)
# depending on what you're doing this might not be necessary...
for k in xrange(0,10):
dflt_dict[k] # accessing any key adds it with the specified default value
print dflt_dict.items()
# [(0, 42), (1, 42), (2, 42), (3, 42), ... (6, 42), (7, 42), (8, 42), (9, 42)]
| |
doc_3223
|
test.cpp
#include "config.h"
int multiply(uint128 *X1, uint128 *Y1, uint128 &ans, int input_length)
{
int i=0;
ans = 0;
if (input_length > 4)
{
for (; i < input_length - 4; i += 4)
{
ans += X1[i] * Y1[i];
ans += X1[i + 1] * Y1[i + 1];
ans += X1[i + 2] * Y1[i + 2];
ans += X1[i + 3] * Y1[i + 3];
}
}
for (; i < input_length; i++)
{
ans += X1[i] * Y1[i];
}
return 0;
}
int main()
{
int len = 500, wrapper = 50;
uint128 a[len], b[len], ans;
auto start = time_now, end = time_now;
long long ctr = 0;
for(int t = 0; t < wrapper; t++)
{
for(int i =0; i < len; i++)
{
a[i] = rand();
b[i] = rand();
}
start = time_now;
multiply(a, b, ans, len);
end = time_now;
ctr += std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count();
}
cout<<"time taken: "<<ctr<<endl;
}
Compilation:
g++ -O3 test.cpp -std=c++11
./a.out
time taken: 1372
optimized.hpp
#ifndef OPTIMIZED_HPP
#define OPTIMIZED_HPP
#include <bits/stdc++.h>
using namespace std;
typedef __uint128_t uint128;
int multiply(uint128 *X1, uint128 *Y1, uint128 &ans, int input_length);
#endif
main.cpp
#include "optimized.hpp"
typedef __uint128_t uint128;
#define time_now std::chrono::high_resolution_clock::now()
int main()
{
int len = 500, wrapper = 50;
uint128 a[len], b[len], ans;
auto start = time_now, end = time_now;
long long ctr = 0;
for(int t = 0; t < wrapper; t++)
{
for(int i =0; i < len; i++)
{
a[i] = rand();
b[i] = rand();
}
start = time_now;
multiply(a, b, ans, len);
end = time_now;
ctr += std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count();
}
cout<<"time taken: "<<ctr<<endl;
return 0;
}
Compilation:
(the name of the library file is optimized.cpp)
g++ -O3 -g -std=c++11 -c optimized.cpp
ar rcs libfast.a optimized.o
g++ main.cpp libfast.a -std=c++11 -O3
./a.out
time taken: 36140
A: I'm afraid you've perpetrated the class foot-shoot: I optimised away the function I was trying to time. We all did it once.
You've optimised the test.cpp program -O3. The compiler observes that the program ignores
the return value of multiply. It also has the definition of multiply to hand
and observes that the body has no external effects but the ignored return value (in any case constant 0) and ignored reference parameter ans. So the line:
multiply(a, b, ans, len);
might as well be:
(void)0;
and the optimiser culls it.
You can rectify this by amending the program so that it uses external effects of multiply in a way that affects the output of the program and can't be predicted just by knowing the definition of the function.
But that's not enough. -O3 optimisation of test.cpp when the
compiler can see the definition of multiply is still going to have
a major information advantage over the same optimisation of main.cpp,
where multiply is just an external reference to a black box.
To measure meaningfully the speed of multiply with -O3
optimisation against its speed with -O0 optimisation you must measure in
each case with other things being equal. So at least do this:
(Inadvertently my test.cpp is your main.cpp)
$ g++ -Wall -Wextra -pedantic -c -O0 -o mult_O0.o optimized.cpp
$ g++ -Wall -Wextra -pedantic -c -O3 -o mult_O3.o optimized.cpp
$ g++ -Wall -Wextra -pedantic -c -O3 -o test.o test.cpp
test.cpp: In function ‘int main()’:
test.cpp:13:13: warning: ISO C++ forbids variable length array ‘a’ [-Wvla]
13 | uint128 a[len], b[len], ans;
| ^
test.cpp:13:21: warning: ISO C++ forbids variable length array ‘b’ [-Wvla]
13 | uint128 a[len], b[len], ans;
| ^
(You might care about those warnings)
$ g++ -o tmult_O0 test.o mult_O0.o
$ g++ -o tmult_O3 test.o mult_O3.o
$ ./tmult_O0
time taken: 228461
$ ./tmult_O3
time taken: 99092
which shows that -O3 is doing its stuff.
And if you do it like that, you don't need to make sure you use the effects of multiply in test.cpp, because now compiler knows that it cannot know the effects of the black box multiply(a, b, ans, len) and cannot cull it.
| |
doc_3224
|
i have a form more or less like this:
<form id="myForm">
<div>
<button type="submit" name="submit">Submit</button>
</div>
<div>
<div id="loading" style="display:none;"><img src="images/loading.gif"/></div>
<div id="hasil" style="display:none;"></div>
</div>
</form>
and a javascript function with ajax :
$('#myForm').submit(function() {
$('#hasil').fadeOut('fast', function() {
alert('a');
$('#loading').fadeIn('fast');
});
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
if(data=='0'){
$('#hasil').html('Code Already Exist');
$('#loading').fadeOut('fast', function() {
alert('d');
$('#hasil').fadeIn();
});
}
}
});
return false;
});
it supposed to show #loading, hide #loading, then show #hasil. at first submit, it will run with no problem. but when i submit it at second time, the script not running at orderly from top to bottom, instead from point 'd', then 'a' (alert()).
i wonder why the script run like this? did i made a mistake somewhere?
A: Reference to jQuery API document: http://api.jquery.com/fadeout/
the callback is fired once the animation is complete.
So, if the ajax request was completed faster than the fade out animation, point 'd' will happen first and then point 'a'.
You can place the ajax request inside the fade out callback function to solve the problem.
$('#myForm').submit(function(e) {
$('#hasil').fadeOut('fast', function() {
alert('a');
$('#loading').fadeIn('fast');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
if(data=='0'){
$('#hasil').html('Code Already Exist');
$('#loading').fadeOut('fast', function() {
alert('d');
$('#hasil').fadeIn();
});
}
}
});
});
return false;
});
| |
doc_3225
|
A Tags table
class Tags(Base):
__tablename__ = 't_tags'
uid = Column(Integer, primary_key=True)
category = Column(Enum('service', 'event', 'attribute', name='enum_tag_category'))
name = Column(String(32))
And a table that maps them to their originating parents
class R_Incident_Tags(Base):
__tablename__ ='r_incident_tags'
incident_uid = Column(String(48), ForeignKey('t_incident.uid'), primary_key=True)
tag_uid = Column(Integer, ForeignKey('t_tags.uid'), primary_key=True)
tag = relationship("Tags", backref="r_incident_tags")
incident_uid is a unique string to identify the parent.
The SELECT I have been struggling to represent in SQLAlchemy is as follows
SELECT DISTINCT s.name, e.name, count(e.name)
FROM "t_tags" AS s,
"t_tags" AS e,
"r_incident_tags" AS sr,
"r_incident_tags" AS er
WHERE s.category='service' AND
e.category='event' AND
e.uid = er.tag_uid AND
s.uid = sr.tag_uid AND
er.incident_uid = sr.incident_uid
GROUP BY s.name, e.name
Any assistance would be appreciated as I haven't even got close to getting something working after a whole day of effort.
Kindest Regards!
A: This should do the job:
s = aliased(Tags)
e = aliased(Tags)
sr = aliased(R_Incident_Tags)
er = aliased(R_Incident_Tags)
qry = (session.query(s.name, e.name, func.count(e.name)).
select_from(s, e, sr, er).
filter(s.category=='service').
filter(e.category=='event').
filter(e.uid == er.tag_uid).
filter(s.uid == sr.tag_uid).
filter(er.incident_uid == sr.incident_uid).
group_by(s.name, e.name)
)
But you could also use relationship-based JOINs instead of simple WHERE clauses.
| |
doc_3226
|
CollegeStudent ima = new CollegeStudent("Ima Frosh", 18, "F", "UCB123",
The following is all of my code for this lab:
TESTING CLASS
public class TestingClass
{
public static void main(String[] args)
{
Person bob = new Person("Coach Bob", 27, "M");
System.out.println(bob);
Student lynne = new Student("Lynne Brooke", 16, "F", "HS95129", 3.5);
System.out.println(lynne);
Teacher mrJava = new Teacher("Duke Java", 34, "M", "Computer Science", 50000);
System.out.println(mrJava);
CollegeStudent ima = new CollegeStudent("Ima Frosh", 18, "F", "UCB123",
4.0, 1, "English");
System.out.println(ima);
}
}
PERSON CLASS
public class Person
{
private String myName ; // name of the person
private int myAge; // person's age
private String myGender; // "M" for male, "F" for female
// constructor
public Person(String name, int age, String gender)
{
myName = name;
myAge = age;
myGender = gender;
}
public String getName()
{
return myName;
}
public int getAge()
{
return myAge;
}
public String getGender()
{
return myGender;
}
public void setName(String name)
{
myName = name;
}
public void setAge(int age)
{
myAge = age;
}
public void setGender(String gender)
{
myGender = gender;
}
public String toString()
{
return myName + ", age: " + myAge + ", gender: " +
myGender;
}
}
TEACHER CLASS
public class Teacher extends Person
{
// instance variables - replace the example below with your own
private String mySubject;
private double myAnnualSalary;
/**
* Constructor for objects of class Teacher
*/
public Teacher(String name, int age, String gender, String Subject, double AnnualSalary)
{
// initialise instance variables
super(name, age, gender);
mySubject = Subject;
myAnnualSalary = AnnualSalary;
}
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public String getSubject()
{
return mySubject;
}
public double getAnnualSalary()
{
return myAnnualSalary;
}
public void setSubject(String Subject)
{
mySubject = Subject;
}
public void setAnnualSalary(double AnnualSalary)
{
myAnnualSalary = AnnualSalary;
}
public String toString()
{
return super.toString() + "Subject:" + mySubject + "Annual Salary:" + myAnnualSalary;
}
}
STUDENT CLASS
public class Student extends Person
{
private String myIdNum; // Student Id Number
private double myGPA; // grade point average
// constructor
public Student(String name, int age, String gender,
String idNum, double gpa)
{
// use the super class' constructor
super(name, age, gender);
// initialize what's new to Student
myIdNum = idNum;
myGPA = gpa;
}
public String getIdNum()
{
return myIdNum;
}
public double getGPA()
{
return myGPA;
}
public void setIdNum(String idNum)
{
myIdNum = idNum;
}
public void setGPA(double gpa)
{
myGPA = gpa;
}
// overrides the toString method in the parent class
public String toString()
{
return super.toString() + ", student id: " + myIdNum + ", gpa: " + myGPA;
}
}
COLLEGE STUDENT CLASS
public class CollegeStudent extends Student
{
// instance variables - replace the example below with your own
private int myYear;
private String myMajor;
/**
* Constructor for objects of class dasf
*/
public CollegeStudent(String idNum, double gpa, String name, int age, String gender, int Year, String Major)
{
// initialise instance variables
super(name, age, gender, idNum, gpa);
myMajor = Major;
myYear = Year;
}
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public String getMajor()
{
return myMajor;
}
public int getYear()
{
return myYear;
}
public void setMajor(String Major)
{
myMajor = Major;
}
public void setYear(int Year)
{
myYear = Year;
}
public String toString()
{
return super.toString() + "Year:" + myYear + "Major:" + myMajor;
}
}
A: // Your call:
CollegeStudent ima = new CollegeStudent("Ima Frosh", 18, "F", "UCB123",
4.0, 1, "English");
// The constructor
public CollegeStudent(String idNum, double gpa, String name,
int age, String gender, int Year, String Major)
As you can see the constructor takes a lot of arguments, and the types matter when doing this.
The types it wants are: String, double, String, int, String, int, String.
However, you are passing: String, int (ok), String, String, double, int, String.
I think you just have the arguments all jumbled, try this:
CollegeStudent ima = new CollegeStudent("UCB123", 4.0, "Ima Frosh", 18,
"F", 1, "English");
A: ..aaand at the end put it like this:
return super.toString() + ", Year: " + myYear + ", Major: " + myMajor;
| |
doc_3227
|
I have built a single, vertical HTML page using jQuery Mobile 1.4.0 and have gotten that working quite nicely.
I then added jQuery Steps 1.0.4 to integrate the wizard aspect and have maintained the majority of the look-and-feel. Unfortunately the jQuery Mobile functionality for most of the form fields has stopped working. For example sliders don't drag, textboxes don't highlight. There are no JS errors, and the fields are initially appearing correctly, just not behaving as they should.
I am wondering if anyone has worked with these two libraries before, has found a work-around, or has any advise on how to approach integrating the two libraries.
<body>
<div id="main">
<form id="" action="landing.html">
<div id="wizard">
<h1>Step 2 - Heading</h1>
<div id="step_2">
<section>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Radio Options</legend>
<input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" />
<label for="radio-choice-1">Option 1</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">Option 2</label>
<input type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3" />
<label for="radio-choice-3">Option 3</label>
</fieldset>
</section>
</div>
</div>
</form>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>
<script src="scripts/libs/jquery.steps-1.0.4.js"></script>
<script src="scripts/initiate.wizard.js"></script>
A: I discovered the answer. As per the author of jQuery Step's issue resolution:
https://github.com/rstaib/jquery-steps/issues/31
I had to delay the auto-initiation of jQuery Mobile until after jQuery Steps has done everything it needs to.
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>window.jQuery || document.write('<script src="scripts/libs/jquery-1.10.2.min.js"><\/script>')</script>
<script src="scripts/libs/jquery.steps-1.0.4.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<script>jQuery.ui || document.write('<script src="scripts/libs/jquery-ui-1.10.4.min.js"><\/script>')</script>
<script>
// delay jQuery Mobile initialisation to allow jQuery Steps initialise first
$(document).on("mobileinit", function () {
$.mobile.autoInitializePage = false;
});
</script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>
<script>$.mobile || document.write('<script src="scripts/libs/jquery.mobile-1.4.0.min.js"><\/script>')</script>
<script src="scripts/initiate.wizard.js"></script>
<script>
// now the DOM should be ready to handle the jQuery Mobile initialisation
$(document).ready(function () {
$.mobile.initializePage();
});
</script>
<script src="scripts/scripts.js"></script>
| |
doc_3228
|
I can easily get this to apply to one tab, but returning to the first active tab and then moving on to the next is giving me no end of trouble.
Ex. code (shortened to the crucial bit). At the bottom where Next is would be where I need to move to the next sheet and do the same function, returning to "Bulksheet" and pasting in the next empty cell in column C.:
Sub
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Activate
Range("C100:F103").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Bulksheet").Select
Range("D1").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next
End Sub
A: Try looping through the sheets using an index value instead.
Sub
Dim i as integer
For i = 1 to worksheets.count
sheets(i).Activate
if activesheet.name <> "Bulksheet" then
Range("C100:F103").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Bulksheet").Select
Range("D1").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
end if
Next
End Sub
A: Try this:
Sub CopyToBulksheet()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Bulksheet" Then
ws.Activate
Range("C1:F10").Copy
Sheets("Bulksheet").Select
Range("D" & Cells.Rows.Count).End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Next
End Sub
| |
doc_3229
|
Model:
public class DataFixingModel {
private ArrayList<String> keys;
private String value;
private String keySelected;
public dataFixingModel() {
this.keys = getKeysValues(); //return ArrayList
this.value = "TMP";
this.keySelected = "abc";
}
....
public ArrayList<String> getKeys() {
return keys;
}
....
Controller:
public class DataFixing {
@RequestMapping(value = "/extra/dataFixing/dataFixing", method = RequestMethod.GET)
public String initCreationTask(ModelMap model) throws ParseException {
DataFixingModel dataFixingModel = new DataFixingModel();
ArrayList<String> urls = dataFixingModel.getKeys();
for (String str:urls){
System.out.println("------key:"+str);
}
//it print all the keys as expected
model.addAttribute("dataFixingModel", dataFixingModel);
return "extra/dataFixing/dataFixing";
}
}
jsp:
<form:form modelAttribute="dataFixingModel" method="POST" class="form-horizontal" cellspacing="2" enctype="multipart/form-data">
....
....
<div class="col-md-4">
<form:select class="form-control input-sm" path="keySelected" data-toggle="tooltip" data-placement="left" title="${title}">
<form:option value="0">--Choose Identifier Type--</form:option>
<form:options items="${keys}"/>
</form:select>
</div>
*
*"TMP" appears fine in the "value" field.
*In other model-controller-jsp the dropdown is populated by the the requested key but not in the above model-controller-jsp.
*I already tried to use array ([]) instead of arraylist).
*In the view source there is no keys under the options.
Am I doing something wrong?
Thanks,
Miki
A: If you have this getter:
public ArrayList<String> getOpenUrlKeys() {
return openUrlKeys;
}
You will get the content with <form:options items="${openUrlKeys}"/>
But does not make much sense because I can't see openUrlKeys variable declared... it should be getKeys() to use <form:options items="${keys}"/>
A: I found the solution:
I replaced: <form:options items="${keys}"/>
with: <form:options items="${dataFixingModel.keys}"/>.
Thanks all!
Mike
| |
doc_3230
|
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string name, Category category)
{
try
{
var oldName = name.ToString();
var newName = category.Name.ToString();
using (var session = _driver.Session())
{
session.WriteTransaction(tx =>
{
tx.Run("Match (a:Category) WHERE a.Name = '$oldName' Set a.Name = '$newName'", new { oldName, newName });
});
}
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
But the code results with no changes. Why?
Model class:
public class Category
{
public string Name { get; set; }
}
And I get the name value from this code in View:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { name = item.Name/* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
A: You don't need to surround the parameters with quotes in your query - Neo4j will sort that out for you.
Try:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string name, Category category)
{
try
{
var oldName = name.ToString();
var newName = category.Name.ToString();
using (var session = _driver.Session())
{
session.WriteTransaction(tx =>
{
tx.Run("Match (a:Category) WHERE a.Name = $oldName Set a.Name = $newName", new { oldName, newName });
});
}
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
In the parameters section, you just need to supply any object whose property names match the names of the parameters in the query. In your example, the new { oldName, newName } section is short-hand for creating an anonymous C# object with two properties, one called oldName and one called newName whose values are taken from the variables you defined.
You could equivalently have a class represent your parameters:
class MyParams {
public string oldName { get; set; }
public string newName { get; set; }
}
var p = new MyParams { oldname = name, newName = category.Name };
tx.Run("Match (a:Category) WHERE a.Name = $oldName Set a.Name = $newName", p);
I prefer the anonymous object approach, your taste may vary.
| |
doc_3231
|
class Publication(models.Model):
title = models.CharField(max_length=128)
author = models.ManyToManyField(Author, through='Authorship')
class Author(models.Model):
first_name = models.CharField(db_index=True, max_length=64)
last_name = models.CharField(db_index=True, max_length=64)
How can I get ALL the publications AND their author(s) in one query. I want to list each publication and its authors on a page.
But I don't want to hit the authors table for every publication.
The only way I know to do it is with select_related in the view and authorship_set.all() on the template. But that's one query for every publication. I could easily do it with raw sql, but that's yucky.
*BTW, I'm using the through model because I have to keep some extra data in there, like author_display_order.
EDIT:
Turns out authorship_set was doing all the querying.
When I run it this way from console only one query gets fired:
pubs = Publication.objects.all().prefetch_related('author')
for p in pubs:
print p.title
for a in p.author.all():
print a.last_name
| |
doc_3232
|
http://jsfiddle.net/ucxpr/4/
Counter Code From Here:
https://github.com/sophilabs/jquery-counter
I have my code setup using the plugins built-in "data-stop" attribute which is currently set at 10... So the counter starts... and counts up to 10 and then stops... I am hoping to trigger the update when the user clicks the #incrementCounter button in my code:
<button id="incrementCounter">Click here</button>
$('#incrementCounter').click(function($) {
$('.counter-analog').attr('data-stop', '25');
});
I figured the best way to increment the counter would just be to modify the data-stop attribute on my span and re-initialize the counter but it doesn't seem to work :-/ ?
Help is greatly appreciated!... Again... I am just trying to figure out a way to make this counter reliably count up to a number that I give it and then stop! :)
I also have tried this with no success:
$('.main_counter .counter-analog').counter({startTime: "25"});
A: Just rerun the counter, but pass the new stop-variable
http://jsfiddle.net/Hed9F/1/
$('#incrementCounter').click(function() {
$('.main_counter .counter-analog').counter({'stop': 25});
});
| |
doc_3233
|
Please note that I must only be able to view the selected record only.. How would I go about this?
echo "<table border='1'>
<tr>
<th>user_id</th>
<th>user_name</th>
<th>selected_product</th>
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
echo "<td>" . $row['user_id'] . "</td>";
echo "<td>" . $row['user_name'] . "</td>";
echo "<td>" . $row['selected_product'] . "</td>";
So a button should appear for each record that is returned as a result. When I click this button another window should appear which shows the entire contents (for this record only) and the user associated.
How does the button know which record its associated with.
A: <a href="anotherpage.php?id=<?php echo $row['user_id']?>" ><button>View Details</button></a>
This will take you to another page.
Use get method tho get the id into php variable.
$userId = $_GET['id'];
And now use sql query to fetch all the data from the database for single user.
$userResult = mysql_query("SELECT * FROM userTable WHERE user_id = ".$userId);
| |
doc_3234
|
char *str;
str = (char *)malloc(sizeof(char) * 10);
I have a const string.
const char *name = "chase";
Because *name is shorter than 10 I need to fill str with chase plus 5 spaces.
I've tried to loop and set str[i] = name[i] but there's something I'm not matching up because I cannot assign spaces to the additional chars. This was where I was going, just trying to fill str with all spaces to get started
int i;
for (i = 0; i < 10; i++)
{
strcpy(str[i], ' ');
printf("char: %c\n", str[i]);
}
A: As the others pointed out, you need
//malloc casting is (arguably) bad
str = malloc(sizeof(char) * 11);
and then, just do
snprintf(str, 11, "%10s", name);
Using snprintf() instead of sprintf() will prevent overflow, and %10swill pad your resulting string as you want.
http://www.cplusplus.com/reference/cstdio/snprintf/
A: If you want str to have 10 characters and still be a C-string, you need to '\0' terminate it. You can do this by mallocing str to a length of 11:
str = malloc(11);
Note there's no need to cast the return pointer of malloc. Also, sizeof(char) is always 1 so there's no need to multiply that by the number of chars that you want.
After you've malloc as much memory as you need you can use memset to set all the chars to ' ' (the space character) except the last element. The last element needs to be '\0':
memset(str, ' ', 10);
str[10] = '\0';
Now, use memcpy to copy your const C-string to str:
memcpy(str, name, strlen(name));
A: easy to use snprintf like this
#include <stdio.h>
#include <stdlib.h>
int main(){
char *str;
str = (char *)malloc(sizeof(char)*10+1);//+1 for '\0'
const char *name = "chase";
snprintf(str, 11, "%-*s", 10, name);//11 is out buffer size
printf(" 1234567890\n");
printf("<%s>\n", str);
return 0;
}
| |
doc_3235
|
simple 18-Jul-2020 15:11:55 Submodule '***' (***) registered for path '***'
simple 18-Jul-2020 15:11:55 Cloning into '***'...
simple 18-Jul-2020 15:11:55 Warning: Permanently added 'vs-ssh.visualstudio.com,**IP**' (RSA) to the list of known hosts.
simple 18-Jul-2020 15:11:56 remote: Public key authentication failed.
simple 18-Jul-2020 15:11:56 fatal: Could not read from remote repository.
simple 18-Jul-2020 15:11:56
simple 18-Jul-2020 15:11:56 Please make sure you have the correct access rights
simple 18-Jul-2020 15:11:56 and the repository exists.
Submodule configured as ssh path.
Base git-repository and git-submodule-repository location at same DevOps Azure.
I see Base git-repository checkout is OK, but git-submodule is not OK.
Where is my wrong?!
A: You can try to create a PAT on azure devops and set up a repo on Bamboo like this:
Authentication type: None
https://<token>@dev.azure.com/<organization>/<project>/_git/<repository>
| |
doc_3236
|
I've added the reference through Visual Studio, written some code that calls a few exposed functions from the service and everything works great.
I'm now trying to change the reference to that web services to another URL, to target another server, ServerB. I BELIEVE the services on these two machines are the same.
However:
ServerA runs some version of the application which includes the deployed web service.
ServerB runs a different version of the application which includes the deployed web service.
Both WSDL contents are identical, the namespace addresses between the two are identical (the target namespace URLs are the same[note that the URLs both reference an external address e.g. http://google.com/services/whatever/]), but my prototype code only works when I reference the web service from ServerA.
I throw a "Fault occurred while processing." exception whenever calling an exposed function on ServerB. From my understanding this is an unhandled exception that is thrown server-side and it does not give me much info to debug.
If these web services were truly identical, would swapping out the endpoint URL in my application configuration be enough to switch references between the two web services or am I grossly misunderstanding something?
| |
doc_3237
|
<available file="XX" property="isXXAvailable"/>
<available file="YY" property="isYYAvailable"/>
For compilation I want to check whether both the properties are true. Only then go ahead with the compilation
<target name="compile" depends="init" unless="isXXAvailable" unless="isYYavailable">
Is it possible to check for both the properties during compiling
A: You can 'AND' two 'available' condtions together into a single one :
<condition property="files.available">
<and>
<available file="XX"/>
<available file="YY"/>
</and>
</condition>
then you can use this condition in the same way you are currently doing in your target
http://ant.apache.org/manual/Tasks/condition.html
| |
doc_3238
|
My head looks like the following:
Index:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index</title>
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../css/style.css" rel="stylesheet" type="text/css">
<link href="../img/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="../js/javascript.js">
</head>
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>brand</title>
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../css/style.css" rel="stylesheet" type="text/css">
<link href="../img/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="../js/javascript.js">
</head>
<body>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.js"></script>
<link href="../vendor/bootstrap/js/bootstrap.min.js">
<nav class="navbar navbar-expand-md navbar-dark">
<!-- Toggler/collapsibe Button -->
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target=".navbar-collapse">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Brand -->
<div class="contains-brand-icon">
<a class="navbar-brand" href="index.html">
<img src="../img/Web-brand.png" loading="lazy" srcset="../img/Web-brand-p-500.png 500w, ../img/Web-brand-p-800.png 800w, ../img/Web-brand-p-1080.png 1080w, ../img/Web-brand.png 1590w" alt="" height="40" id="brand-icon-navbar" class="justify-content-center">
</a>
</div>
<!-- Navbar -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="brand-app.html">BrandApp</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">brand für Unternehmen</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">brand für Organisationen</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Kampangen</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Über uns</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Support</a>
</li>
</ul>
</div>
</nav>
<div class="fixed-top">
<nav>
<div class="navBar">
<ul>
<li>
<a href="index.html"><img src="../img/Web-brand.png" loading="lazy" srcset="../img/Web-brand-p-500.png 500w, ../img/Web-brand-p-800.png 800w, ../img/Web-brand-p-1080.png 1080w, ../img/Web-brand.png 1590w" alt="" id="navbar-icon-brand"></a>
</li>
<li><a href="brand-app.html">BrandApp</a></li>
<li><a href="#">brand für Unternehmen</a></li>
<li><a href="#">brand für Organisationen</a></li>
<li><a href="#">Kampangen</a></li>
<li><a href="#">Über uns</a></li>
<li><a href="#">Support</a></li>
</ul>
</div>
</nav>
</div>
<div class="introduction-brand">
<div class="container">
<div class="row">
<div class="introduction-brand-innerpart">
<h1 class="heading">brand App</h1>
<div class="sub-heading">Spenden wird kostenlos.</div>
<div class="sub-sub-heading">Ohne Anmeldung, versteckte Kosten oder Abonnements.</div>
<div class="linking">
<a href="index.html">Weitere Infos ></a>
<a href="index.html">Herunterladen ></a>
</div>
</div>
<div id="cut-phones">
<div id="cut-phones" class="col-sm-12 mobile-presentation">
<img src="../img/smartmockups_kldnit2k.png" loading="lazy" width="310" sizes="(max-width: 479px) 100vw, 310px" srcset="../img/smartmockups_kldnit2k-p-500.png 500w, ../img/smartmockups_kldnit2k-p-800.png 800w, ../img/smartmockups_kldnit2k-p-1080.png 1080w, ../img/smartmockups_kldnit2k.png 1570w" alt="" class="mobile-presentation-leftest">
<img src="../img/smartmockups_kldnk32x.png" loading="lazy" width="350" sizes="(max-width: 479px) 100vw, 350px" srcset="../img/smartmockups_kldnk32x-p-500.png 500w, ../img/smartmockups_kldnk32x-p-800.png 800w, ../img/smartmockups_kldnk32x-p-1080.png 1080w, ../img/smartmockups_kldnk32x.png 1570w" alt="" class="mobile-presentation-left">
<img src="../img/smartmockups_kldneqvz.png" loading="lazy" width="310" sizes="(max-width: 479px) 100vw, 310px" srcset="../img/smartmockups_kldneqvz-p-500.png 500w, ../img/smartmockups_kldneqvz-p-800.png 800w, ../img/smartmockups_kldneqvz-p-1080.png 1080w, ../img/smartmockups_kldneqvz.png 1571w" alt="" class="mobile-presentation-rightest">
<img src="../img/smartmockups_kldnfsiz.png" loading="lazy" width="350" sizes="(max-width: 479px) 100vw, 350px" srcset="../img/smartmockups_kldnfsiz-p-500.png 500w, ../img/smartmockups_kldnfsiz-p-800.png 800w, ../img/smartmockups_kldnfsiz-p-1080.png 1080w, ../img/smartmockups_kldnfsiz.png 1571w" alt="" class="mobile-presentation-right">
<img src="../img/smartmockups_kldnld5u.png" loading="lazy" width="380" sizes="(max-width: 479px) 100vw, 380px" srcset="../img/smartmockups_kldnld5u-p-500.png 500w, ../img/smartmockups_kldnld5u-p-800.png 800w, ../img/smartmockups_kldnld5u-p-1080.png 1080w, ../img/smartmockups_kldnld5u.png 1480w" alt="" class="mobile-presentation-centre">
</div>
</div>
</div>
</div>
</div>
</body>
</html>
SecondPage:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>brand App</title>
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../css/style.css" rel="stylesheet" type="text/css">
<link href="../img/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="../js/javascript.js">
</head>
<body>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.js"></script>
<link href="../vendor/bootstrap/js/bootstrap.min.js">
<nav class="navbar navbar-expand-md navbar-dark">
<!-- Toggler/collapsibe Button -->
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target=".navbar-collapse">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Brand -->
<div class="contains-brand-icon">
<a class="navbar-brand" href="index.html">
<img src="../img/Web-brand.png" loading="lazy" srcset="../img/Web-brand-p-500.png 500w, ../img/Web-brand-p-800.png 800w, ../img/Web-brand-p-1080.png 1080w, ../img/Web-brand.png 1590w" alt="" height="40" id="brand-icon-navbar" class="justify-content-center">
</a>
</div>
<!-- Navbar -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">BrandApp</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">brand für Unternehmen</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">brand für Organisationen</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Kampangen</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Über uns</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Support</a>
</li>
</ul>
</div>
</nav>
<div class="fixed-top">
<nav>
<div class="navBar">
<ul>
<li>
<a href="index.html"><img src="../img/Web-brand.png" loading="lazy" srcset="../img/Web-brand-p-500.png 500w, ../img/Web-brand-p-800.png 800w, ../img/Web-brand-p-1080.png 1080w, ../img/Web-brand.png 1590w" alt="" id="navbar-icon-brand"></a>
</li>
<li><a href="#">BrandApp</a></li>
<li><a href="#">brand für Unternehmen</a></li>
<li><a href="#">brand für Organisationen</a></li>
<li><a href="#">Kampangen</a></li>
<li><a href="#">Über uns</a></li>
<li><a href="#">Support</a></li>
</ul>
</div>
</nav>
</div>
<div class="introduction-brand-app">
<div class="container">
<div class="row">
<div class="col-sm-12 mobile-presentation-brand-app">
<img src="../img/smartmockups_kldnit2k.png" loading="lazy" width="310" sizes="(max-width: 479px) 100vw, 310px" srcset="../img/smartmockups_kldnit2k-p-500.png 500w, ../img/smartmockups_kldnit2k-p-800.png 800w, ../img/smartmockups_kldnit2k-p-1080.png 1080w, ../img/smartmockups_kldnit2k.png 1570w" alt="" class="mobile-presentation-leftest-brand-app">
<img src="../img/smartmockups_kldnk32x.png" loading="lazy" width="350" sizes="(max-width: 479px) 100vw, 350px" srcset="../img/smartmockups_kldnk32x-p-500.png 500w, ../img/smartmockups_kldnk32x-p-800.png 800w, ../img/smartmockups_kldnk32x-p-1080.png 1080w, ../img/smartmockups_kldnk32x.png 1570w" alt="" class="mobile-presentation-left-brand-app">
<img src="../img/smartmockups_kldneqvz.png" loading="lazy" width="310" sizes="(max-width: 479px) 100vw, 310px" srcset="../img/smartmockups_kldneqvz-p-500.png 500w, ../img/smartmockups_kldneqvz-p-800.png 800w, ../img/smartmockups_kldneqvz-p-1080.png 1080w, ../img/smartmockups_kldneqvz.png 1571w" alt="" class="mobile-presentation-rightest-brand-app">
<img src="../img/smartmockups_kldnfsiz.png" loading="lazy" width="350" sizes="(max-width: 479px) 100vw, 350px" srcset="../img/smartmockups_kldnfsiz-p-500.png 500w, ../img/smartmockups_kldnfsiz-p-800.png 800w, ../img/smartmockups_kldnfsiz-p-1080.png 1080w, ../img/smartmockups_kldnfsiz.png 1571w" alt="" class="mobile-presentation-right-brand-app">
<img src="../img/smartmockups_kldnld5u.png" loading="lazy" width="380" sizes="(max-width: 479px) 100vw, 380px" srcset="../img/smartmockups_kldnld5u-p-500.png 500w, ../img/smartmockups_kldnld5u-p-800.png 800w, ../img/smartmockups_kldnld5u-p-1080.png 1080w, ../img/smartmockups_kldnld5u.png 1480w" alt="" class="mobile-presentation-centre-brand-app">
</div>
</div>
</div>
</div>
</body>
</html>
CSS:
/**
* index
*/
html, body {
max-width: 100%;
overflow-x: hidden;
}
body {
margin: 0;
background-color: #faf9f9;
}
.fixed-top{
display: none;
}
@media (min-width: 768px) {
.fixed-top{
display: inline-block;
width: 100%;
}
.navbar{
display: none;
}
nav {
height: 44px;
background: rgba(0,0,0,0.93);
}
nav ul {
display: flex;
height: 44px;
justify-content: space-around;
align-items: center;
padding: 0;
margin: 0 auto;
list-style-type: none;
}
nav a {
display: block;
color: white;
font-size: 15px;
font-weight: lighter;
text-decoration: none;
transition: 0.3s;
}
nav a:hover {
color: #B8B8B8;
text-decoration: none;
}
.navBar {
max-width: 980px;
margin: 0 auto;
}
}
#collapsibleNavbar{
justify-content: center;
text-align: center;
}
.nav-item a{
border-top: 1px solid grey;
font-size: 15px;
font-weight: lighter;
transition: 0.3s;
}
.navbar-brand {
transform: translateX(-50%);
left: 50%;
position: absolute;
top: 0;
margin-top: 8px;
}
#navbar-icon-brand {
height: 55px;
}
.navbar{
background: rgba(0,0,0,0.93);
overflow: hidden;
}
.navbar-toggler {
border-color: rgba(0,0,0,0)!important;
}
.introduction-brand-innerpart {
margin: 0 auto;
margin-top: 4rem;
margin-bottom: 2rem;
text-align: center;
width: 100%;
}
@media(min-width: 768px){
#navbar-icon-brand {
margin-top: 5px;
height: 40px;
}
.introduction-brand-innerpart {
margin: 0 auto;
margin-top: 8rem;
margin-bottom: 4rem;
text-align: center;
width: 100%;
}
}
.heading {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-right: auto;
margin-left: auto;
margin-bottom: 0;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
color: #000;
font-size: 36px;
font-weight: 400;
text-align: center;
}
.sub-heading {
margin-top: 0px;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-right: auto;
margin-left: auto;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
color: #000;
font-size: 21px;
font-weight: 300;
}
.sub-sub-heading {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-top: -5px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
color: #a6a6a6;
font-size: 13px;
font-weight: lighter;
}
.linking {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-top: 10px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
font-size: 17px;
font-weight: 400;
}
.linking a{
display: block;
font-size: 11px;
text-decoration: none;
transition: 0.3s;
padding-right: 20px;
padding-left: 20px;
font-weight: bolder;
}
@media (min-width: 576px) {
.heading {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-right: auto;
margin-left: auto;
margin-bottom: 0;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
color: #000;
font-size: 50px;
font-weight: 400;
}
.sub-heading {
margin-top: -10px;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-right: auto;
margin-left: auto;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
color: #000;
font-size: 26px;
font-weight: 300;
}
.sub-sub-heading {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-top: -5px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
color: #a6a6a6;
font-size: 15px;
font-weight: lighter;
}
.linking {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-top: 10px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
font-size: 14px;
font-weight: 400;
}
.linking a{
display: block;
font-size: 14px;
text-decoration: none;
transition: 0.3s;
padding-right: 35px;
padding-left: 35px;
font-weight: bolder;
}
}
@media (min-width: 992px) {
.heading {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-right: auto;
margin-left: auto;
margin-bottom: 0;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
color: #000;
font-size: 80px;
font-weight: 400;
}
.sub-heading {
margin-top: -10px;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-right: auto;
margin-left: auto;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
color: #000;
font-size: 32px;
font-weight: 300;
}
.sub-sub-heading {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-top: -5px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
color: #a6a6a6;
font-size: 20px;
font-weight: lighter;
}
.linking {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-top: 10px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
font-size: 17px;
font-weight: 400;
}
.linking a{
display: block;
font-size: 15px;
text-decoration: none;
transition: 0.3s;
padding-right: 35px;
padding-left: 35px;
font-weight: bolder;
}
}
.mobile-presentation {
position: relative;
margin-top: auto;
margin-right: auto;
margin-left: auto;
border: 1px none #000;
background-color: hsla(0, 0%, 98.4%, 0);
left: -50%;
text-align: center;
}
.mobile-presentation-leftest {
position: absolute;
display: block;
margin-top: 40px;
margin-right: auto;
margin-left: -70px;
width: 150px;
height: auto;
}
.mobile-presentation-left {
position: absolute;
display: block;
margin-top: 25px;
margin-right: auto;
margin-left: -45px;
width: 160px;
height: auto;
}
.mobile-presentation-rightest {
position: absolute;
display: block;
margin-top: 40px;
margin-right: auto;
margin-left: 85px;
width: 150px;
height: auto;
}
.mobile-presentation-right {
position: absolute;
display: block;
margin-top: 25px;
margin-right: auto;
margin-left: 51px;
width: 160px;
height: auto;
}
.mobile-presentation-centre {
position: relative;
display: block;
margin-top: 0;
margin-right: auto;
margin-left: auto;
width: 170px;
height: auto;
}
@media (min-width: 576px) {
.mobile-presentation-leftest {
position: absolute;
display: block;
margin-top: 40px;
margin-right: auto;
margin-left: -110px;
width: 170px;
height: auto;
}
.mobile-presentation-left {
position: absolute;
display: block;
margin-top: 25px;
margin-right: auto;
margin-left: -70px;
width: 190px;
height: auto;
}
.mobile-presentation-rightest {
position: absolute;
display: block;
margin-top: 40px;
margin-right: auto;
margin-left: 135px;
width: 170px;
height: auto;
}
.mobile-presentation-right {
position: absolute;
display: block;
margin-top: 25px;
margin-right: auto;
margin-left: 77px;
width: 190px;
height: auto;
}
.mobile-presentation-centre {
position: relative;
display: block;
margin-top: 0;
margin-right: auto;
margin-left: auto;
width: 200px;
height: auto;
}
}
@media (min-width: 992px) {
.mobile-presentation {
position: relative;
margin-top: auto;
margin-right: auto;
margin-left: auto;
border: 1px none #000;
background-color: hsla(0, 0%, 98.4%, 0);
left: -50%;
}
.mobile-presentation-leftest {
position: relative;
display: block;
margin-top: 134px;
margin-right: auto;
margin-left: 11px;
width: auto;
}
.mobile-presentation-left {
position: relative;
display: block;
margin-top: -504px;
margin-right: auto;
margin-left: 90px;
width: auto;
}
.mobile-presentation-rightest {
position: relative;
display: block;
margin-top: -508px;
margin-right: auto;
margin-left: 585px;
width: auto;
}
.mobile-presentation-right {
position: relative;
display: block;
margin-top: -504px;
margin-right: auto;
margin-left: 465px;
width: auto;
}
.mobile-presentation-centre {
position: relative;
display: block;
margin-top: -584px;
margin-right: auto;
margin-left: auto;
width: auto;
}
}
#cut-phones {
height: 350px;
position: static;
margin-top: auto;
margin-right: auto;
margin-left: auto;
border: 1px none #000;
background-color: hsla(0, 0%, 98.4%, 0);
left: -50%;
}
/**
*
* Brand App
*
*/
.mobile-presentation-brand-app {
position: relative;
margin-top: 14rem;
margin-right: auto;
margin-left: auto;
border: 1px none #000;
background-color: hsla(0, 0%, 98.4%, 0);
}
.mobile-presentation-leftest-brand-app {
position: relative;
display: block;
margin-top: 134px;
margin-right: auto;
margin-left: 122px;
width: auto;
}
.mobile-presentation-left-brand-app {
position: relative;
display: block;
margin-top: -504px;
margin-right: auto;
margin-left: 212px;
width: auto;
}
.mobile-presentation-rightest-brand-app {
position: relative;
display: block;
margin-top: -508px;
margin-right: auto;
margin-left: 656px;
width: auto;
}
.mobile-presentation-right-brand-app {
position: relative;
display: block;
margin-top: -504px;
margin-right: auto;
margin-left: 535px;
width: auto;
}
.mobile-presentation-centre-brand-app {
position: relative;
display: block;
margin-top: -584px;
margin-right: auto;
margin-left: auto;
width: auto;
}
I thought the problem might come from my head, but as you can see, they are identical.
The resolutions are the following:
Index resolution: 1903 x 733
SecondPage resolution: 2114.44 x 904.12
The resolution doesn't differ, even when I delete all html code.
The resolution difference is done by my browser. When I look at the responsive design of the site, everything is fine. But as soon as I start to use the site without the responsive tool by Chrome, the navbar starts moving when I switch from one page to another. This is because the resolution of the second page is wider than my index page.
I just tried the site on Edge. Everything works fine there. The site does not become wider by itself. But this still doesn't fix my problem on Chrome.
Any idea why Chrome behaves so weird?
A: The "error" was that I zoomed out of the window and Chrome saved the zoom preferences. Additionally the page had no scrollbar like the other pages and therefore was not pushed to the side.
| |
doc_3239
|
A: Just have save a boolean in shared preference. If boolean is false reload Frag A and if its true reload Frag B. Depending on where the user left off use can store Shared preference. I am assuming that you want to recreate last seen fragment on app closed and then opened.
| |
doc_3240
|
var response = await client.SearchAsync<MenuForElasticSearch>(searchDescriptor => searchDescriptor
.Query(queryContainerDescriptor => queryContainerDescriptor
.Bool(queryDescriptor => queryDescriptor
.Should(queryStringQuery => queryStringQuery.Match(match => match.Field(fld => fld.DisplayName).Query(query)),
queryStringQuery => queryStringQuery.Wildcard(wildcard => wildcard.Field(flds => flds.DisplayName).Value($"*{query}*")),
queryStringQuery => queryStringQuery.Fuzzy(fuzzy => fuzzy.Field(flds => flds.DisplayName).Value(query)))
)));
There are three documents with displayName = NPW-711, NPW-677 and NPW-777. When I search NPW-711 it returns all three documents.
Can adding DefaultOperator(Elasticsearch.Net.DefaultOperator.And) help? If yes, where it fits?
A: Match query with AND operator will give you what you are looking for
var results = await client.SearchAsync<Document>(s => s
.Query(q => q
.Match(m => m
.Field("name")
.Query(query)
.Operator(Operator.And))));
output:
Results for query "NPW-777": NPW-777
Results for query "NPW": NPW-711,NPW-677,NPW-777
Results for query "677": NPW-677
Hope that helps.
| |
doc_3241
|
Regards, Jan van de Klok
A: Jan:
If it's enough to avoid making an update when another user has changed the document concurrently, you can enable optimistic locking:
http://docs.marklogic.com/guide/java/transactions#id_81051
You can also use a multistatement transaction if you want to perform several related changes and have all or none succeed:
http://docs.marklogic.com/guide/java/transactions#id_79848
Hoping that helps,
Erik Hennum
A: It is also not very difficult to leverage the DLS functions from within custom REST extensions. Adam Fowler did some work on that, and made that available on github:
https://github.com/adamfowleruk/mljs/tree/dev/apps/workplace/rest-api/ext
And here javascript code that shows how to use it, search in it for 'dls', and you should be able to find the relevant part:
https://github.com/adamfowleruk/mljs/blob/dev/src/js/mljs.js
With regard to getting started, I'd recommend looking at the interactive tutorials at:
http://developer.marklogic.com/learn
HTH!
| |
doc_3242
|
It works perfectly with the following code:
atmt.SaveAsFile
Some emails however contain an email attachment that contain the desired file.
How do i extract such a second-level attachment?
A: UPDATE: Thank you all for your suggestions. The following works:
For Each atmt In zMsg.Attachments 'Loop through attachments
atmt.SaveAsFile DestPath & atmt.FileName
Set zMsg2 = Application.CreateItemFromTemplate(DestPath & atmt.FileName)
For Each atmt2 In zMsg2.Attachments
atmt2.SaveAsFile DestPath & atmt2.FileName
Next
Set zMsg2 = Nothing
Kill DestPath & atmt.FileName
Next
| |
doc_3243
|
I'm assuming the saving to file would have to be achieved in PHP by performing a Ajax post request with the relevant data. But whenever I attempt to post to a simple php test file I get a 400 bad request error.
Im not using a browser to perform the ajax requests (using console commands in conEmu64), which i think is the issue when attempting a HttpRequest. The ajax get request works fine at retrieving the data from api, just unsure why this error happens on the post requests to local PHP file.
*
*Can anyone suggest best approach at Ajax posting without a browser?
*Should I instead be attempting to save the CSV purely in java script?
Attempt 1: Basic Javascript & XMLHttpRequest Module
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
function createCSV(request) {
var xhr = new XMLHttpRequest;
xhr.open('POST', 'server/save');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log(xhr);
if (xhr.status === 200) {
console.log('Name is now ' + xhr.responseText);
}
else if (xhr.status !== 200) {
console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(JSON.stringify({
name: 'John Smith',
age: 34
}));
}
Attempt 2: Axios Module
const axios = require('axios');
function createCSV(request) {
axios.post('server/save', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
Simple video reqirements
A: You can use node to do this. Have you tried using something like FS?
This answer was originally posted here Write to a CSV in Node.js
You can use fs (https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback):
var infoReturnedFromAxiosGet;
var timeStamp;
var fs = require('fs');
fs.writeFile('yourfoldername/' + timeStamp + '.csv', infoReturnedFromAxiosGet, 'utf8', function (err) {
if (err) {
console.log('Some error occured - file either not saved or corrupted file saved.');
} else{
console.log('It\'s saved!');
}
});
| |
doc_3244
|
I am using unicode arrow at the value using the chart's numberSuffix. This effects all the numbers on the chart. Is there a way to just apply it only on the value?
I did use annotations before trying this out but scaling messes up with the arrow placement.
A: I have found another way of implementing the above mentioned feature.
A small hack into the code.
Here is the fiddle link.
Although accessing internal objects for implementation is not supported by FusionCharts as it is subjected to change.
FusionCharts.addEventListener('rendered', function(e) {
var dataset = e.sender.jsVars.instanceAPI.components.dataset[0],
labelEle = dataset.graphics.dataLabel && dataset.graphics.dataLabel[0];
labelEle && (labelEle.attr({
text: labelEle.attrs.text + " ↓"
}));
});
A: You can use annotations for this requirement.
Here is a workaround.
Fiddle
<div id="chart-container">FusionCharts will render here</div>
| |
doc_3245
|
I have no idea how to go about doing this, I have googled and found nothing that will help me understand what I need to do. Also, how would I go about doing this if the rectangle was at an angle, say 45 degree slope?
Any help appreciated.
Thanks
Tom
A: Tom, if you are new to Game world you need to search more about game engine for android.
Actually you need to search more about collision detection in android.
for more help try to read more about this game engine :
http://www.andengine.org/
there are lots of engines but you need to learn them.
Regards,
| |
doc_3246
|
PrintDocument pDoc = new PrintDocument();
PrintLayoutSettings PrintLayout = new PrintLayoutSettings();
PrinterSettings printerSettings = new PrinterSettings();
printerSettings.PrinterName = pq.printerName;
PageSettings pSettings = new PageSettings(printerSettings);
crReportDocument.PrintOptions.DissociatePageSizeAndPrinterPaperSize = true;
crReportDocument.PrintOptions.PrinterDuplex = PrinterDuplex.Simplex;
OnMessageLogged(TraceEventType.Information, "PrePrint " + crReportDocument.PrintOptions.PrinterName);
WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero);
try
{
crReportDocument.PrintToPrinter(printerSettings, pSettings, false, PrintLayout);
OnMessageLogged(TraceEventType.Information, "Printed " + pq.printerName);
}
catch (Exception eprint)
{
OnMessageLogged(TraceEventType.Information, "****Failed to Print** to printer " + pq.printerName + " Exception " + eprint.ToString());
}
finally
{
// Resume impersonation
ctx.Undo();
OnMessageLogged(TraceEventType.Information, "Success Printing to " + pq.printerName);
}
When I call the PrintToPrinter method:
crReportDocument.PrintToPrinter(printerSettings, pSettings, false, PrintLayout);
It takes up to two and a half minutes to execute. I see this behavior whether I run the code in Visual Studio, or as a deployed service on a server.
We recently upgraded our services servers, and our print servers to windows 2012. Before, our services server was Windows 2008, and our print server was Windows 2003. We did not have this problem with that set up.
Has anyone experienced problems with printing to a printer taking a long time, or problems printing to a Win2012 Print Server?
Thanks?
A: Use
_report.ReportClientDocument.PrintOutputController.PrintReport(popt);
instead of _report.PrintToPrinter, it is 5-10x faster.
My code example:
CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions popt = new CrystalDecisions.ReportAppServer.Controllers.PrintReportOptions();
popt.PrinterName = printerSettings.PrinterName;
_report.ReportClientDocument.PrintOutputController.PrintReport(popt);
Tested on CR 13.06., PrintToPrinter took ~3800 miliseconds while PrintReport only ~320
A: This problem is caused by a bug in the crystal 13 basic runtime.
Setting the printer name is ignored if the report has been saved with the no printer option. So, the developer has to assign the entire PrinterSettings property of the report document. This is where the delay occurs.
// This is the old and reliable way - didn't work for version 13
Settings = new PrinterSettings();
Settings.PrinterName = "HP Printer";
// you don't even need the PrinterSettings object in 10.5, just the printer name
_report.PrintOptions.PrinterName = Settings.PrinterName;
// for version 13 you have to assign the printer settings
if(_report.PrintOptions.PrinterName != Settings.PrinterName)
_report.PrintToPrinter(Settings, new PageSettings(), false);
I had upgraded from 10.5 (basic 2008) which printed very quickly, but had to undergo a difficult rollback because of this (unacknowledged) bug.
I am currently researching the sp 10 from Crystal to see if this issue has been resolved.
EDIT
The issue with slow PrintToPrinter has now been resolved, however SAP have recommended we use:
report.ReportClientDocument.PrintOutputController.PrintReport(options);
instead of PrintToPrinter, which will get no further development.
| |
doc_3247
|
This question describes a way to suppress the unused parameter warning by writing a macro inside the function code:
Universally compiler independent way of implementing an UNUSED macro in C/C++
But I'm interested in a macro that can be used in the function signature:
void callback(int UNUSED(some_useless_stuff)) {}
This is what I dug out using Google (source)
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#elif defined(__cplusplus)
# define UNUSED(x)
#else
# define UNUSED(x) x
#endif
Can this be further expanded for other compilers?
Edit: For those who can't understand how tagging works: I want a solution for both C and C++. That is why this question is tagged both C and C++ and that is why a C++ only solution is not acceptable.
A: After testing and following the comments, the original version mentioned in the question turned out to be good enough.
Using: #define UNUSED(x) __pragma(warning(suppress:4100)) x (mentioned in comments), might be necessary for compiling C on MSVC, but that's such a weird combination, that I didn't include it in the end.
A: Across many compilers I have used the following, excluding support for lint.
#if (__GNUC__ > 2) || (__GNUC__ == 2 && __GNUC_MINOR__ > 4)
# define PGM_GNUC_UNUSED __attribute__((__unused__))
#else
# define PGM_GNUC_UNUSED
#endif
Tested compilers: GCC, Clang, EKOPath, Intel C Compiler / Composer XE, MinGW32 on Cygwin / Linux / MSYS, MinGW-w64 on Cygwin / Linux, Sun ONE Studio / Oracle Solaris Studio, Visual Studio 2008 / 2010.
Example usage:
pgm_tsc_init (
PGM_GNUC_UNUSED pgm_error_t** error
)
{
...
}
PGM is the standard prefix for this C based project. GNUC is the convention from GLib for this attribute.
I think one compile warns about __attribute__ in certain circumstances but certainly no error.
A: The way I do it is like this:
#define UNUSED(x) (void)(x)
void foo(const int i) {
UNUSED(i);
}
I've not had a problem with that in Visual Studio, Intel, gcc and clang.
The other option is to just comment out the parameter:
void foo(const int /*i*/) {
// When we need to use `i` we can just uncomment it.
}
A: Just one small thing, better using __attribute__((__unused__)) as __attribute__((unused)), because unused could be somewhere defined as macro, personally I had a few issues with this situation.
But the trick I'm using is, which I found more readable is:
#define UNUSED(x) (void)x;
It works however only for the variables, and arguments of the methods, but not for the function itself.
| |
doc_3248
|
#include <windows.h>
#include <mmsystem.h>
#pragma comment( lib, "Winmm.lib" )
using namespace std;
int main()
{
PlaySound(L"C:\Users\Lol\Downloads\Music\Undertale OST - Hotel Extended.wav", 0, SND_FILENAME);
return 0;
}
And it gives me an error:
incomplete universal character name \U|
Also before that it says:
ignoring #pragma comment [-Wunknown-pragmas]|
What is wrong here?
A:
incomplete universal character name \U|
In character and string literals, certain escape sequences have special meaning to the compiler:
Your string literal contains 2 instances of the \U escape sequence, however there are no numeric values following the \U to make up the digits of valid Unicode codepoints, hence the compiler error.
To use actual \ characters in your string literal, you need to escape them as \\, eg:
L"C:\\Users\\Lol\\Downloads\\Music\\Undertale OST - Hotel Extended.wav"
Or, if you are using C++11 or later, you can use a raw string literal, which uses a slightly different syntax that does not require you to escape characters manually:
LR"(C:\Users\Lol\Downloads\Music\Undertale OST - Hotel Extended.wav)"
ignoring #pragma comment [-Wunknown-pragmas]|
How you link to .lib files is very toolchain-specific. Your compiler (you did not say which one you are using) is telling you that it does not support the #pragma comment(lib, ...) directive. So, you will have to link to Winmm.lib in another way that is more appropriate for your particular toolchain's linker. Read the documentation for your toolchain.
| |
doc_3249
|
Dictionary<int, Dictionary<int, StructuredCell>> CellValues = new Dictionary<int, Dictionary<int, StructuredCell>>();
inside a class StructuredTable. I would like to be able to write a loop as
StructuredTable table = new StructuredTable();
// Fill the table with values
foreach(StructuredCell cell in table.Cells()) {
// Fill an alternate structure
}
Where any x,y combination inside the bound of the max of the number of columns and rows is returned as null. I can't seem to locate an example that uses yield this way.
A: Something like
public IEnumerable<StructuredCell> Cells(){
for (int i = 0; i < maxColumn; i++)
{
Dictionary<int, StructuredCell> row = null;
CellValues.TryGetValue(i, out row);
for (int j = 0; j < maxRow; j++)
{
if (row == null) yield return null;
StructuredCell cell = null;
row.TryGetValue(j, out cell);
yield return cell;
}
}
}
A: Based on the fact that the keys are resonable small you can do a number of optimizations here.
public class DataStructure {
private const int MAX_VALUE = 100000;
private readonly Dictionary<long, StructuredCell> CellValues;
private void Add(int keyOne, int keyTwo, StructuredCell cell) {
long hashKey = keyOne*MAX_VALUE + keyTwo;
CellValues[hashKey] = cell;
}
private void Remove(int keyOne, int keyTwo)
{
long hashKey = keyOne * MAX_VALUE + keyTwo;
CellValues.Remove(hashKey);
}
private IEnumerable<StructuredCell> GetCells() {
return CellValues.Values;
}
}
You can keep a simple Key->Value dictionary, where the
key = hash(keyOne, keyTwo)
You don't need any fancy lazy constructs (yield) since you already have the values available.
| |
doc_3250
|
Now I stumbled upon other frameworks (like Gxt3) that use one large table but with table-layout: fixed. How does this approach compare to the "decoupled" (sorry for not having a better term here, maybe there exists one) table described above? Does this have the same performance benefit?
Examples
Standard table
<table>
<tbody>
<tr>
<td>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
"Decoupled"
<div>
<table>
<tbody>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
</div>
| |
doc_3251
|
*
*Use shell command or shell script.
*For example, I have one word: sport.
*I want to get another word: oprst.
Now I want to use shell to bring about it, how to do? Thanks!
A: Use the following Shell Script:-
#!/bin/sh
sortedWord=`echo $1 | grep -o . | sort |tr -d "\n"`;
echo $sortedWord;
| |
doc_3252
|
A: Since Jersey 2.23, there's a LoggingFeature you could use. The following is a bit simplified example, please note that you can register the feature on WebTarget as well.
Logger logger = Logger.getLogger(getClass().getName());
Feature feature = new LoggingFeature(logger, Level.INFO, null, null);
Client client = ClientBuilder.newBuilder()
.register(feature)
.build();
Response response = client.target("https://www.google.com")
.queryParam("q", "Hello, World!")
.request().get();
JavaDoc of LoggingFeature says that the request "and/or" the response is logged lol. On my machine, both are logged.
A: @ivan.cikic's answer is for Jersey 1.x. Here's how you do it in Jersey 2.x:
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.filter.LoggingFilter;
import org.json.JSONException;
import org.json.JSONObject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
...
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
client.register(new LoggingFilter());
This is irrelevant but I just have to complain: The new LoggingFilter is really annoying because it forces you to use Java Util Logging. It would be better if it gave me control over the logger. Seems like a step backwards in design.
A: All these answers are pretty close but they lack the setting to log the request and response body. At least with Jersey 2.30.1 this is how I accomplish logging the request and response including their respective bodies:
import javax.ws.rs.client.ClientBuilder;
import org.glassfish.jersey.logging.LoggingFeature;
import java.util.logging.Level;
import java.util.logging.Logger;
Logger logger = Logger.getLogger("LoggingFeature");
logger.setLevel(Level.ALL);
ClientBuilder.newClient()
.target("https://www.example.com")
.register(new LoggingFeature(
logger,
Level.ALL,
LoggingFeature.Verbosity.PAYLOAD_ANY,
8192))
.request()
.get();
Technically the Level.All and 8192 values could be null. I just provide them here to be concise.
A: If you're just using Jersey Client API, LoggingFilter (client filter) should help you:
Client client = Client.create();
client.addFilter(new LoggingFilter(System.out));
WebResource webResource = client.resource("http://localhost:9998/");
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
Otherwise, you can again log both request and response on server using other LoggingFilter (container filter).
A: For the Version 3.1.X it mus be:
Logger logger = Logger.getLogger("test");
LoggingFeature loggingFeature = new LoggingFeature(logger, Level.INFO, Verbosity.PAYLOAD_ANY,null);
Client client = ClientBuilder.newClient();
client.register(loggingFeature);
Level.ALL is NOT Working
| |
doc_3253
| ||
doc_3254
|
void setup() {
size(600, 480, P3D);hint(ENABLE_DEPTH_SORT);
}
void draw()
{
background(0);
translate(width/2, height/2); fill(color(255,255,255),84);
strokeWeight(0);
translate(-40,0,1);sphere(80);
translate(2*40,0,0);sphere(80);
// Fails with corruption: http://i.imgur.com/GW2h7Qv.png
}
Note: sphereDetail need not apply. sphereDetail(60) causes fail with loss of left overlap:
A: To understand why this is happening, you have to understand what's going on under the hood.
##Think in Triangles
When you call the sphere() function, Processing is actually drawing a bunch of triangles. You can see this if you run this simple program:
size(500, 500, P3D);
translate(width/2, height/2);
sphere(100);
In your code, you have chosen to not draw the outline, but Processing is still drawing a bunch of triangles to draw your sphere. Here is what it draws with sphereDetail(10):
The point is, you need to stop seeing spheres, and see the triangles that make up those spheres.
##Depth Buffering
OpenGL (and therefore Processing) uses depth buffering to figure out when not to draw something that's behind something else.
I'm just going to copy a section of this article, which explains it much better than I can:
Consider this example of drawing two triangles, A and B:
(source: windows.net)
If we draw B first, then A, the depth buffer will see that the new
pixels from A are closer than the ones previously drawn by B, so it
will draw them over the top. If we draw in the opposite order (A
followed by B) the depth buffer will see that the pixels coming in
from B are further away than the ones already drawn by A, so it will
discard them. In either case we get the correct result: A is on top,
with B hidden behind it.
When you're drawing an opaque sphere, you're really drawing a bunch of opaque triangles. Processing will draw these triangles in whatever order the sphere-to-triangle algorithm generated them. This works for opaque objects, since Processing will check the Z-buffer and then skip over triangles that are behind triangles that were already drawn. That's basically as smart as OpenGL gets out of the box.
##The Problem with Transparency
Again, quoting the article:
But what if this geometry is alpha blended, so B is partially visible
through the translucent A triangle? This still works if we draw B
first, then A over the top, but not if we draw A followed by B. In
that case, the depth buffer will get a pixel from B, and notice that
it has already drawn a closer pixel from A, but it has no way to deal
with this situation. It’s only choices are to draw the B pixel (which
will give the wrong result, because it would be blending the more
distant B over the top of the closer A, and alpha blending is not
commutative) or it could discard B entirely. Not good!
The problem is, this doesn't work for transparent triangles. Remember that Processing is drawing the triangles in whatever order the algorithm generated them, and it's using the Z-buffer to decide when to skip over triangles that are behind already-drawn triangles. But we don't want it to skip over any triangles! We want to draw every triangle, because we want to be able to see the back triangles through the front triangles.
For example, if we draw a transparent gray sphere in front, and then we draw a red sphere behind it, we won't see the red sphere.
size(500, 500, P3D);
translate(width/2, height/2);
noStroke();
//front gray sphere
fill(255, 255, 255, 64);
sphere(100);
//back red sphere
translate(0, 0, -500);
fill(255, 0, 0, 64);
sphere(100);
I'm using entire spheres here because I'm lazy, but imagine this exact problem happening for the individual triangles in each sphere. This is why you see those artifacts in the gray sphere, for the same reason you can't see the red sphere behind the gray sphere. OpenGL draws the gray sphere first, but then it skips over the red sphere because it knows that it's behind the front sphere. This is the correct behavior for opaque objects, but we're complicating things by adding transparency.
##Drawing Order Matters
If instead we draw the back red sphere before we draw the front gray sphere, then we see the red sphere through the gray sphere:
size(500, 500, P3D);
translate(width/2, height/2);
noStroke();
//back red sphere
translate(0, 0, -500);
fill(255, 0, 0, 64);
sphere(100);
//front gray sphere
translate(0, 0, 500);
fill(255, 255, 255, 64);
sphere(100);
Note that we still see artifacts within each sphere because of the triangle order problem. This is happening for the same reason we couldn't see the red sphere when we draw it after the gray sphere.
Now, to fix the issue with the triangles, drawing order matters. Exactly like you have to draw the front gray sphere after you draw the back red sphere, you have to draw the triangles from the back to the front, that way OpenGL doesn't skip over any that it determines are behind an already-drawn triangle. This is a huge pain in the neck.
##Processing to the Rescue
Luckily, Processing has an option to do this for you. That's the hint(ENABLE_DEPTH_SORT) function. With this enabled, Processing will sort every triangle by the average Z position of its three vertices, and then draw them in that order. With this enabled, we can draw the back red sphere after the front gray sphere, and Processing will sort the triangles for us and draw them in the correct order before it gets to OpenGL:
size(500, 500, P3D);
hint(ENABLE_DEPTH_SORT);
translate(width/2, height/2);
noStroke();
//front gray sphere
fill(255, 255, 255, 64);
sphere(100);
//back red sphere
translate(0, 0, -500);
fill(255, 0, 0, 64);
sphere(100);
Notice that we can see the back red sphere, even though we're drawing it after the front gray sphere. Processing is intervening on our behalf and sorting the triangles before actually drawing them in OpenGL. This also fixes the artifacts within each sphere, since the triangles are sorted in each sphere, not just between spheres.
##The Problem with Intersection
Remember that the triangles are sorted by the average Z position of their 3 vertices. This is a problem for triangles that intersect. This is the crux of your issue.
From the article, imagine that you have two triangles A and B that intersect like this:
(source: windows.net)
There is no possible way to sort these triangles, because we need to
draw the top part of B over A, but the bottom part of A over B. The
only solution is to detect when this happens and split the triangles
where they intersect, but that would be prohibitively expensive.
Which triangle should be drawn first? There isn't a single answer, but Processing is going to do its best and sort them according to the average Z position of their 3 vertices. This is causing the artifacts you're seeing.
We can see this in a simple interactive sketch:
void setup() {
size(500, 500, P3D);
hint(ENABLE_DEPTH_SORT);
noStroke();
}
void draw() {
background(128);
translate(width/2, height/2);
//gray sphere
fill(255, 255, 255, 64);
sphere(100);
//red sphere
translate(0, 0, mouseY-width/2);
fill(255, 0, 0, 64);
sphere(100);
}
Move your mouse up and down to move the red sphere front or back. As it intersects with the gray sphere, you get the artifacts because the triangles are intersecting.
(Ignore the artifacts around the mouse, that's a result of creating a gif.)
This is the cause of the artifacts you're seeing.
##Possible Solutions
What can you do to fix it? You've got a few options:
Option 1: Stop using transparency. Many of your issues are caused by using transparency, which makes things very complicated. The quickest and easiest thing to do would be to stop using transparency, as OpenGL works best with opaque objects.
Option 2: Stop using shapes that intersect. You can think of your intersecting spheres as impossible objects, which OpenGL doesn't handle very well. Could you simply move your shapes so they aren't intersecting? If you're trying to build a complex shape, maybe use a 3D model or construct it yourself using the vertex() function?
Option 3: Come up with your own sorting algorithm. Processing uses the average Z position, which isn't guaranteed to be correct when you have intersecting shapes. Instead of relying on Processing to sort the triangles, you could do it yourself. How you'd do that goes beyond this question, and it sounds super annoying, but that's the nature of 3D rendering.
Option 4: If you really, really, really need to have intersecting transparent shapes, then the only correct thing to do is to detect intersections and then split them up into subshapes that you then draw in the correct order. This is very very very annoying, but you're going down an annoying path.
You might also investigate shaders. I don't really know anything about shaders, but anytime I see an issue with 3D rendering, somebody inevitably comes along and says the answer is to use a shader. So that might be worth looking into (it also might not be worth looking into, I honestly don't know), although you're on your own with that one.
| |
doc_3255
|
Here is basically the function I'm calling for each browser event:
function xhr_event(timeStamp){
xhr=new XMLHttpRequest()
xhr.open("POST",'/record_event');
console.log(timeStamp.toString())
xhr.send(timeStamp.toString())
}
where timeStamp=event.timeStamp
On the client side, each event logs to console. On the server side, not all events appear to POST. To the best I can tell, lost events are random.
I read about browser caching but I don't think that can be the problem, since each payload has a unique time stamp? Then again I'm not doing any encoding or setting of headers, so maybe that's the issue?
A: As @mottek mentioned and explained in the comments, adding a var (or let or const) before xhr solved the problem.
I didn't realize xhr=new XMLHTTPRequest() creates a global variable.
I also got the post to work consistently by using fetch:
fetch('/record_event', {
method: 'post',
headers: {
'Content-Type':'text/plain'
}
body: timeStamp.toString()
}
| |
doc_3256
|
[DataType(DataType.Date)]
public DateTime? Date1 { get; set; }
[DataType(DataType.Date)]
public DateTime? Date2 { get; set; }
[DataType(DataType.Date)]
public DateTime? Date3 { get; set; }
It's important for Data1 to Data3 to be DateTime?
My problem:
//Return right value
(model.Date1.ToString().AsDateTime().ToShortDateString() != "01.01.0001" ? model.Date1.ToString().AsDateTime().ToShortDateString() : "Is not known")
//Return bad value
(model.Date2.ToString().AsDateTime().ToShortDateString() != "01.01.0001" ? model.Date1.ToString().AsDateTime().ToShortDateString() : "Není známo")
//Return bad value
(model.Date3.ToString().AsDateTime().ToShortDateString() != "01.01.0001" ? model.Date3.ToString().AsDateTime().ToShortDateString() : "Is not known")
I dont know how or why but input is same but Date2 and Date3 returns bad value...
Thanks for any help
A: You can use the nullable types as follows.
model.Date1.HasValue ? model.Date1.Value.ToShortDateString() : "Unknown";
A: You can also compare with default datetime value by model.Date1.GetValueOrDefault() != default(DateTime).
GetValueOrDefault will return default value if Date1 is null.
model.Date1.GetValueOrDefault() != default(DateTime) ? model.Date1.Value.ToShortDateString() : "Unknown";
| |
doc_3257
|
I am trying to make a single query where I split the two values of 'Y' and 'N' into two different columns based on the id and count the total number of times they appear for each id.
SELECT exerciseId, count(frustrated) Frustrated from selfreportfrustration where frustrated = 'Y' group by exerciseId;
SELECT exerciseId, count(frustrated) NotFrustrated from selfreportfrustration where frustrated = 'N' group by exerciseId;
So far I have only managed to make one query for each value, but I was hoping to be able to shorten it into one query for my program to work.
A: You can use conditional aggregation:
select exerciseId, sum(frustrated = 'Y') as Frustrated,
sum(frustrated = 'N') as NotFrustrated
from selfreportfrustration
group by exerciseId;
A: We'll put the 'Y' or 'N' in another column:
SELECT frustrated, exerciseId,
count(frustrated) Frustrated
from selfreportfrustration
group by frustrated, exerciseId;
A: You can use Count() aggregation with If() conditional function.
Try:
SELECT exerciseId,
COUNT( IF(frustrated = 'Y', exerciseId, NULL) ) AS frustrated,
COUNT( IF(frustrated = 'N', exerciseId, NULL) ) AS not_frustrated
FROM selfreportfrustration
GROUP BY exerciseId
| |
doc_3258
|
The most promising approach I have tried was converting let's say a string 01001101 to a decimal number 77, then converting number 77 into encoding table character M, then writing M into new file, which will create a file with 01001101 digital bits. This awkward solution however corrupts data, because some binary values are not processed correctly. Here is the code:
This part creates text ones and zeroes from digital data file:
$SourceFile = "C:\Users\Admin\Desktop\test.bin"
$TargetFile = "C:\Users\Admin\Desktop\test.bin" + "_clean"
$filestream = New-Object IO.FileStream -ArgumentList $SourceFile, ([IO.FileMode]::Open), ([IO.FileAccess]::Read)
$filestream.Position = 0
$bytebuffer = New-Object "Byte[]" -ArgumentList 128
[void]$filestream.Read($bytebuffer, 0, $bytebuffer.Length)
$filestream.Close()
$OnesZeroes = $bytebuffer -split "`n" | ForEach-Object {
[System.Convert]::ToString($_,2).PadLeft(8,'0')
}
This part tries to convert text ones and zeroes back to digital data:
$RawData = $OnesZeroes | ForEach-Object {[CHAR]([CONVERT]::toint32($_,2))}
$RawData = $RawData -join ""
$OutputRAW = [System.IO.StreamWriter] $TargetFile
$filesize = (Get-Item $SourceFile).length
[void]$OutputRAW.Write($RawData, 0, $filesize)
$OutputRAW.close()
Somebody might be wondering, why I'm trying to perform such a strange operation. I need to statistically process and modify individual bits in a large file, where individual portions of data are not an integer number of bytes. In particular to compare bit by bit first 1150 bits to the second 1150 bits and to the third 1150 bits and so on in a set of 16x1150 bits, where whole file has about 2000 sets of 16x1150 bits. I do not know, how to process individual bits, so I made a awkward workaround by converting bits to "1" and "0" bytes first.
A: According to my further research and a good tip from LotPings using .net BitArray class seems to be an universal answer for all the difficulties. After some trial and error I finally get the .net BitArray class approach working!
$SourceFile = "C:\Users\Admin\Desktop\test.bin"
$FileSize = (Get-Item $SourceFile).length
$SourceBytes = [System.IO.File]::ReadAllBytes($SourceFile)
$BitArray = [System.Collections.BitArray]($SourceBytes)
$BitArray.Set(15746, 0) #Modify one bit as a test
$ByteArray = New-Object Byte[] $FileSize
$BitArray.Copyto($ByteArray,0)
[System.IO.File]::WriteAllBytes($SourceFile + "_clean", $ByteArray)
Now I can manipulate individual bits as booleans and save the result as binary file.
| |
doc_3259
|
Every time I click on 'show' for an individual article on the index, it opens a blank page with a URL like localhost:3000/articles.1, instead of localhost:3000/articles/1.
I don't know what's wrong with the code, it's similar to the code I have for creating and editing articles as admin and it works there, but I keep getting this error.
Here's the code:
views/articles/show.html.erb:
<h1><%= @article.name %></h1>
<%= @article.content %>
<%= image_tag @article.photo.url(:small) %>
<p>Tags: <%= raw article.tag_list.map { |t| link_to t, tag_path(t) }.join(', ') %></p>
<%= link_to 'Back', noticias_path %>
views/articles/index.html.erb:
<% @articles.each do |article| %>
<div>
<h2><%= article.name %></h2>
<%= article.content %>
<p><%= link_to 'Show', noticias_path(article) %></p>
<p>Tags: <%= raw article.tag_list.map { |t| link_to t, tag_path(t) }.join(', ') %></p>
</div>
<% end %>
articles_controller.rb:
# GET /articles/1
# GET /articles/1.json
def show
@article = Article.find(params[:id])
end
routes.rb:
Blog::Application.routes.draw do
root to: 'welcome#index'
get 'tags/:tag', to: 'noticias#index', as: :tag
get "noticias/index"
get "dashboard/index"
get "/sitemap" => "sitemap#index", :as => :sitemap, :defaults => {:format => :xml}
match '/noticias', to: 'noticias#index', via: 'get'
get 'login', to: 'sessions#new', as: 'login'
get 'logout', to: 'sessions#destroy', as: 'logout'
resources :users
resources :sessions
namespace :admin do
get '', to: 'dashboard#index', as: '/'
resources :noticias
end
end
A: It's more a problem with noticias_path, consider verify your routes with rake routes, but I think to change noticias_path to noticia_path, may can fixed it.
A: Based on your routes file, it looks like the problem is indeed incorrect routing. Presently, you are manually creating routes for RESTful resources, when you should simply let rails handle that for you properly.
Remove the manual get and match lines:
get "noticias/index"
match '/noticias', to: 'noticias#index', via: 'get'
And replace them with this:
resources :noticias
If noticias should be pointing to the ArticlesController (or any other controller), then simply do this:
resources :noticias, to: 'articles'
Also, Matheus Caceres was correct that the URL helper should in fact be noticia_path for the show action. The noticias_path points to the index action. Rails tries to be "helpful" by making routes, helpers, functions, etc, sound proper if read in English, but might not necessarily make sense for words in another language. I don't know if "noticia" makes any sense in Portuguese though.
Another quick side note, the two manual routing lines I indicated above are redundant; they would in fact both match a GET request and route them to noticias#index. However, keep in mind that routes are matched in the order they appear in the routing file, so the match line would never have been called, since the route would have matched on that get line.
| |
doc_3260
|
I'm open to having vanilla be a subdomain or a subdirectory (or controller/action), I'm just trying to get this working without having to hack Vanilla or Yii too much.
Currently, I've included Yii's yii.php file inside of Vanilla's index.php file, and I can access Yii classes this way. But I'm not entirely sure how to render the Yii layout from inside of Vanilla. Can any of you help me out? Thanks!
| |
doc_3261
|
I want to convert 0000411111 to 0411111 get rid of the first three zeros
<cfset origValue = "#query.column#">
<cfset newValue = ReReplace(origValue, "0+", "", "all")>
<cfoutput>#newValue#</cfoutput>
This removes all zeros is there anyway to just keep one zero. Just curious.
Thanks in advance for your assistances.
A: If the string will always be 7 characters you can use
<cfset newValue = numberFormat(000411111,'0000000')>
If you don't know the length and always want to remove leading 0's and leave one at the begining you can do
<cfset newValue = '0' & int(000411111)>
A: If you always want to remove the first three characters, you can use the right() function:
<cfset newValue = right(query.column, len(query.column)-3>
This will return all the characters from the right side of the string without the leading three characters.
A: You could do it 2 different ways:
<Cfset newvalue=right(origvalue,len(origvalue)-3>
This method returns the string without the left 3 most characters
or
<Cfset newvalue=mid(origvalue,4,len(origvalue)-3>
this method starts at position 4 and grabs the rest of the string.
A: I think the numberFormat() answer is the best one, but other people have been suggesting using mid() and right() which I think - whilst those approaches work - are more cumbersome than you need to make it. If you simply wish to remove the first three chars of the string, there's a removeChars() function. It's unclear from your question though whether this actually achieves what you want: if it's only when the number is left-padded with too many zeros you want to do this, then the numberFormat() approach is best. If it's any three characters, then this approach is better.
newValue = removeChars(origValue, 1, 3);
A: The regex string you are looking for really is for matching 2 or more 0's at the start of the string, and replacing them with simply a single 0.
This gives the regex ^0+0
^ matches the start of the string, 0+ matches 1 or more 0's, 0 matches the second zero. This will mean that if there is only 1 leading zero then it won't need to do anything. Finally you only need to do this once, as you are only replacing the ones at the start of the string. This brings to the CF code
newValue = ReReplace(origValue, "^0+0", "0", "one")
This should replace multiple leading zeros with a single one, while not adding zeros where there weren't any to begin with.
As a final note, a good place to play around with regex is http://gskinner.com/RegExr/
| |
doc_3262
|
*
*student without grades detail
*student with gardes detail
First API I am using is to return a student without grade detail.
The endpoint for this API is
api/students/{studentId}
and the other API will return the list of the students with grades object in it.
I am confused about how to make a restful route for this problem?
I have tried
api/students/grades/{studentId}
is this the right way to return a student with his grades detail?
A: This question is well described in the "Use logical nesting on endpoints" section of the Best practices for REST API design article.
If you follow REST guidelines
*
*/students - should return list of all students; optionally filtering, sorting, and pagination can be added, for example, through query parameters;
*/students/{id} - should return basic information about a specific student;
*/students/{id}/grades - should return grades details for a specific student.
| |
doc_3263
|
A: After trial and error here is an example:
const applySelect = (event) => {someFunction(event.target.value)};
const selectedValue = 3;
return (
<FormGroup controlId="formControlsSelect">
<ControlLabel >Label String</ControlLabel>
<FormControl componentClass="select" placeholder="select" value={selectedValue} onChange={applySelect}>
<option value="0" key="0">Option 0</option>
<option value="1" key="1">Option 1</option>
<option value="2" key="2">Option 2</option>
</FormControl>
</FormGroup>
| |
doc_3264
|
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("USER_ID", Uid);
builder.addTextBody("SERIAL_NO", Srno);
builder.addTextBody("CUST_NO", CUST_NO);
builder.addTextBody("SESSION_ID", Sid);
File file = new File(filepaths.get(0));
Log.d("file",file.getName());
// builder.addBinaryBody("file[]", file,
// ContentType.create("*/*"), file.getName());
builder.addPart("file[]",new FileBody(file));
for image i am getting sucess in response, in loading pdf i am getting some issue. how do i add pdf to the server using this code?
| |
doc_3265
|
"""
├─myapp
| ├─mypackge
| ├─init.py
| ├─a.py
│ ├─b.py
| ├─c.py
"""
#a.py
class A:
pass
#b.py
from mypackge.a import A
class B(A):
pass
#c.py
from a import A as A1
from mypackge.a import A as A2
from b import B
print(A1, A2) # output: <class 'a.A'> <class 'mypackage.a.A'>
print(issubclass(B, A1)) # output: False
print(issubclass(B, A2)) # output: True
# Next, I try to modify the c.py file using globals()
from a import A as A1
from mypackage.a import A as A2
from b import B
from pprint import pprint
pprint(globals())
print('-' * 50)
globals()['A1'] = A2
pprint(globals())
print(issubclass(B, A1))
print(issubclass(B, A2))
# ouput:
"""
{'A1': <class 'a.A'>,
'A2': <class 'mypackage.a.A'>,
'B': <class 'b.B'>,
...
--------------------------------------------------
{'A1': <class 'mypackage.a.A'>,
'A2': <class 'mypackage.a.A'>,
'B': <class 'b.B'>,
...
True
True
"""
| |
doc_3266
|
Executable named git not found on path:
listing several different directories/paths but not the specific folder where I have it downloaded. I apologise if this question has already been answered (I did try googling and looking up similar questions, but I had trouble understanding the solutions).
Additional note: I installed stack manually from github (commercialhaskell) instead of using their command as the command didn't work for me.
A: You'll need to install the git source code management system. This is very widely used for programming in all languages, so the stack installation instructions might just assume you have it already.
| |
doc_3267
|
@Entity
@Table(name = "player_account")
public class PlayerAccount {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@ManyToOne(targetEntity = Player.class, fetch = FetchType.EAGER)
@JoinColumn(name="player_id")
private Player player;
//GET, SET methods
}
The question is do we actual have to specify that many-to-one raltionship in the database when we're creating a table? I mean to define a references in the following way:
CREATE TABLE player_account (
SERIAL UNIQUE,
player_id integer REFERENCES players
);
A: No you don't need to define in database; but that foreign key column should be present in table. i.e. player_id should be present in player_account table.
| |
doc_3268
|
I have a list of list of int, i.e. List<List<int>> . Assume each list of int contains unique items. The minimum size of the list is 5. I need to find exactly two lists of int (List A and List B) that share exactly three common items and another list of int (List X) that contains exactly one of these common items. Another condition must hold: none of the other lists contain any of these three items.
For example:
List<List<int>> allLists = new List<List<int>>();
allLists.Add(new List<int>() {1, 2, 3, 4});
allLists.Add(new List<int>() {1, 2});
allLists.Add(new List<int>() {3, 4});
allLists.Add(new List<int>() {3, 4, 5, 6, 7, 8, 9});
allLists.Add(new List<int>() {4, 6, 8});
allLists.Add(new List<int>() {5, 7, 9, 11});
allLists.Add(new List<int>() {6, 7, 8});
For the above example, I would hope to find a solution as:
ListA and ListB: [3, 5] // indices of allLists
ListX: 6 // index of allLists
The three shared items: [5, 7, 9]
The matching item in ListX: 7
Note: Depending on the content of lists, there may be multiple solutions. There may be also situations that no lists is found matching the above conditions.
I was stuck in some messy nested loops. I was thinking if anyone may come up with a simple and efficient solution (possibly with LINQ?)
Originally I had something stupid like the following:
for (var i = 0; i < allLists.Count - 1; i++)
{
if (allLists[i].Count > 2)
{
for (var j = i + 1; j < allLists.Count; j++)
{
List<int> sharedItems = allLists[i].Intersect(allLists[j]).ToList();
if (sharedItems.Count == 3)
{
foreach (var item in sharedItems)
{
int itemCount = 0;
int? possibleListXIndex = null;
for (var k = 0; k < allLists.Count; k++)
{
if (k != i && k != j && allLists[k].Contains(item))
{
// nested loops getting very ugly here... also not sure what to do....
}
}
}
}
}
}
}
Extended Problem
There is an extended version of this problem in my project. It is in the same fashion:
*
*find exactly three lists of int (List A, List B and List C) that share exactly four common items
*find another list of int (List X) that contains exactly one of the above common items
*none of the other lists contain these four items.
I was thinking the original algorithm may become scalable to also cover the extended version without having to write another version of algorithm from scratch. With my nested loops above, I think I will have no choice but to add at least two deeper-level loops to cover four items and three lists.
I thank everyone for your contributions in advance! Truly appreciated.
A: Here's a solution that comes up with your answer. I wouldn't exactly called it efficient, but it's pretty simple to follow.
It breaks the work in two step. First it constructs a list of initial candidates where they have exactly three matches. The second step adds the ListX property and checks to see if the remaining criteria is met.
var matches = allLists.Take(allLists.Count - 1)
.SelectMany((x, xIdx) => allLists
.Skip(xIdx + 1)
.Select(y => new { ListA = x, ListB = y, Shared = x.Intersect(y) })
.Where(y => y.Shared.Count() == 3))
.SelectMany(x => allLists
.Where(y => y != x.ListA && y != x.ListB)
.Select(y => new
{
x.ListA,
x.ListB,
x.Shared,
ListX = y,
SingleShared = x.Shared.Intersect(y)
})
.Where(y => y.SingleShared.Count() == 1
&& !allLists.Any(z => z != y.ListA
&& z != y.ListB
&& z != y.ListX
&& z.Intersect(y.Shared).Any())));
You get the output below after running the following code.
ListA. 3: [3, 4, 5, 6, 7, 8, 9] ListB. 5: [5, 7, 9, 11] => [5, 7, 9], ListX. 6:[6, 7, 10] => 7
matches.ToList().ForEach(x => {
Console.WriteLine("ListA. {0}: [{1}] ListB. {2}: [{3}] => [{4}], ListX. {5}:[{6}] => {7}",
allLists.IndexOf(x.ListA),
string.Join(", ", x.ListA),
allLists.IndexOf(x.ListB),
string.Join(", ", x.ListB),
string.Join(", ", x.Shared),
allLists.IndexOf(x.ListX),
string.Join(", ", x.ListX),
string.Join(", ", x.SingleShared));
A: I will leave the exercise of further work such as which list matches which other one given your fairly generic requirement. So here, I find those that match 3 other values in a given array, processing all arrays - so there are duplicates here where an A matches a B and a B matches an A for example.
This should give you something you can work from:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var s = new List<int>();
List<List<int>> allLists = new List<List<int>>();
allLists.Add(new List<int>()
{1, 2, 3, 4});
allLists.Add(new List<int>()
{1, 2});
allLists.Add(new List<int>()
{3, 4});
allLists.Add(new List<int>()
{3, 4, 5, 6, 7, 8, 9});
allLists.Add(new List<int>()
{4, 6, 8});
allLists.Add(new List<int>()
{5, 7, 9, 11});
allLists.Add(new List<int>()
{6, 7, 8});
/*
// To iterate over it.
foreach (List<int> subList in allLists)
{
foreach (int item in subList)
{
Console.WriteLine(item);
}
}
*/
var countMatch = 3;
/* iterate over our lists */
foreach (var sub in allLists)
{
/* not the sub list */
var ns = allLists.Where(g => g != sub);
Console.WriteLine("Check:{0}", ns.Count()); // 6 of the 7 lists so 6 to check against
//foreach (var glist in ns) - all of them, now refactor to filter them:
foreach (var glist in ns.Where(n=> n.Intersect(sub).Count() == countMatch))
{
var r = sub.Intersect(glist); // get all the matches of glist and sub
Console.WriteLine("Matches:{0} in {1}", r.Count(), glist.Count());
foreach (int item in r)
{
Console.WriteLine(item);
}
}
}
}
}
This will output this:
Hello World
Check:6
Check:6
Check:6
Check:6
Matches:3 in 3
4
6
8
Matches:3 in 4
5
7
9
Matches:3 in 3
6
7
8
Check:6
Matches:3 in 7
4
6
8
Check:6
Matches:3 in 7
5
7
9
Check:6
Matches:3 in 7
6
7
8
A: I think it would be better to break this functionality into several methods, then it will look easier to read.
var allLists = new List<List<int>>();
allLists.Add(new List<int>() {1, 2, 3, 4});
allLists.Add(new List<int>() {1, 2});
allLists.Add(new List<int>() {3, 4});
allLists.Add(new List<int>() {3, 4, 5, 6, 7, 8, 9});
allLists.Add(new List<int>() {4, 6, 8});
allLists.Add(new List<int>() {5, 7, 9, 11});
allLists.Add(new List<int>() {6, 7, 8});
var count = allLists.Count;
for (var i = 0; i < count - 1; i++)
{
var left = allLists[i];
if (left.Count > 2)
{
for (var j = i + 1; j < count; j++)
{
var right = allLists[j];
var sharedItems = left.Intersect(right).ToList();
if (sharedItems.Count == 3)
{
for (int k = 0; k < count; k++)
{
if (k == i || k == j)
continue;
var intersected = allLists[k].Intersect(sharedItems).ToList();
if (intersected.Count == 1)
{
Console.WriteLine($"Found index k:{k},i:{i},j:{j}, Intersected numbers:{string.Join(",",intersected)}");
}
}
}
}
}
}
A: I just thought if I try to find the item in List X first, I might need fewer loops in practice. Correct me if I am wrong.
public static void match(List<List<int>> allLists, int numberOfMainListsToExistIn, int numberOfCommonItems)
{
var possibilitiesToCheck = allLists.SelectMany(i => i).GroupBy(e => e).Where(e => (e.Count() == numberOfMainListsToExistIn + 1));
foreach (var pGroup in possibilitiesToCheck)
{
int p = pGroup.Key;
List<int> matchingListIndices = allLists.Select((l, i) => l.Contains(p) ? i : -1).Where(i => i > -1).ToList();
for (int i = 0; i < matchingListIndices.Count; i++)
{
int aIndex = matchingListIndices[i];
int bIndex = matchingListIndices[(i + 1) % matchingListIndices.Count];
int indexOfListXIndex = (i - 1 + matchingListIndices.Count) % matchingListIndices.Count;
int xIndex = matchingListIndices[indexOfListXIndex];
IEnumerable<int> shared = allLists[aIndex].Intersect(allLists[bIndex]).OrderBy(e => e);
IEnumerable<int> xSingle = shared.Intersect(allLists[xIndex]);
bool conditionsHold = false;
if (shared.Count() == numberOfCommonItems && xSingle.Count() == 1 && xSingle.Contains(p))
{
conditionsHold = true;
for (int j = 2; j < matchingListIndices.Count - 1; j++)
{
int cIndex = matchingListIndices[(i + j) % matchingListIndices.Count];
if (!Enumerable.SequenceEqual(shared, allLists[aIndex].Intersect(allLists[cIndex]).OrderBy(e => e)))
{
conditionsHold = false;
break;
}
}
if (conditionsHold)
{
List<int> theOtherListIndices = Enumerable.Range(0, allLists.Count - 1).Except(matchingListIndices).ToList();
if (theOtherListIndices.Any(x => shared.Intersect(allLists[x]).Count() > 0))
{
conditionsHold = false;
}
}
}
if (conditionsHold)
{
matchingListIndices.RemoveAt(indexOfListXIndex);
Console.Write("List A and B: {0}. ", String.Join(", ", matchingListIndices));
Console.Write("Common items: {0}. ", String.Join(", ", shared));
Console.Write("List X: {0}.", xIndex);
Console.WriteLine("Common item in list X: {0}. ", p);
}
}
}
}
For the above example, I will just call the method like this:
match(allLists, 2, 3);
This method will also work with the extended problem:
match(allLists, 3, 4);
... and even more if the problem is even further more extended to (4, 5) and so on...
| |
doc_3269
|
"jsfiddle net/DC2Ry/2"
A: I have altered your fiddle. Did you mean for the top buttons to be dropdowns themselves?
link: http://jsfiddle net/qrf4bcj3/1/
EDIT
Check this bad boy out:
http://jsfiddle net/qrf4bcj3/2/
| |
doc_3270
|
what is the best approach as per you for version deployment with the warm handover(without any connection loss) from app-v1 to app-v2?
A: The question seems to be about supporting two versions at the same time. That is kind of Canary deployment, which make production traffic to gradually shifting from app-v1 to app-v2.
This could be achieved with:
*
*Allow deployments to have HPA with custom metric that based on number of connections. That is, when it reaches certain number of connections scale up/down.
*Allow two deployments at the same time, app-v1 and app-v2.
*Allow new traffic to route on new deployment via some Ingress annotation, but still keeping access to the old version, so no existing connection be dropped.
*Now, all the new requests will be routed to the new version. The HPA eventually, scale down pods from old version. (You can even allow deployment to have zero replicas).
Addition to your question above blue-green deployments.
The blue-green deployment is about having two identical environments, where one environment active at a time, let's say blue is active on production now. Once you have a new version ready for deployment, say green, is deployed and tested separately. Finally, you switched the traffic to the green environment, when you are happy with the test result on green environment. So green become active while blue become idle or terminated later sometime.
(Referred from martin fowler article).
In Kubernetes, this can be achieved with having two identical deployments. Here is a good reference.
Basically, you can have two identical deployments, assume you have current deployment my-deployment-blue is on production. Once you are ready with the new version, you can deploy it as a completely new deployment, lets say my-deployment-green, and use a separate test service to test the green environment. Finally, switch the traffic to the my-deployment-green when all test are passed.
A: If you are trying to achieve Blue/Green in Kubernetes then my answer might help you.
Do a rolling update by setting the following configuration
*
*maxUnavailable = 0
*maxSurge = 100%
How?
The deployment controller first scales the latest version up to 100% of the obsolete version. Once the latest version is healthy, it immediately scales the obsolete version down to 0%.
Example Code:
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
strategy:
rollingUpdate:
maxSurge: 100%
maxUnavailable: 0
type: RollingUpdate
| |
doc_3271
|
class CRoot { ... };
class CLevelOne { ... };
class CLevelTwo { ... };
Now, I have main function, where I'd like to go more in depth by using this syntax:
int main (void)
{
CRoot myRoot ("This is root.");
myroot.AddLevelOne("This is level one.").AddLevelTwo("This is level two.");
}
So the final construction of my classes looks like this:
+- This is root.
|+- This is level one.
||+- This is level two.
How to implement it so I can use syntax something.Method1().Method2().MethodN(). ...; ?
A: Something like this:
struct CLevelTwo { };
struct CLevelOne {
CLevelTwo * AddLevelTwo() {
return new CLevelTwo();
}
};
struct CRoot {
CLevelOne * AddLevelOne() {
return new CLevelOne();
}
};
int main(){
CRoot *root = new CRoot();
root->AddLevelOne()->AddLeveTwo();
}
You can replace the pointers with references, but beware of memory leaks. Note that this code leaks too, but it is more manageable and managing lifetime of the objects should not be a big problem.
A: Try this:
struct Level2
{
// See class Level1 below
};
struct Level1
{
std::string m_name;
boost::shared_ptr<Level2> p_level2;
Level1(const std::string name)
: name(m_name)
{ ; }
Level2& add_level_two(const std::string& name)
{
p_level2 = new Level2(name);
}
};
struct Root
{
boost::shared_ptr<Level1> p_level1;
Level1& add_level_one(const std::string& name)
{
p_level1 = new Level1(name);
}
};
With a little more thought, a base class, one could create this more generically. Also the level numbers would have to be moved out of the method names.
A: Just make SomeMethod return a reference of *this:
struct Foo
{
Foo& Add(SomeOtherThing& thing)
{
// Do the "add"...
return *this;
}
};
Now you can do:
Foo myFoo;
myFoo.Add(...).Add(...).Add(...);
It's just like how the assignment operator overload works.
A: Edit After reviewing this with Thibaut, I propose the following solution:
class Node
{
private:
std::string _name;
std::list<Node*> _nodes;
public:
Node(const std::string& name) : _name(name)
{
}; // eo ctor
virtual ~Node()
{
for(std::list<Node*>::iterator it(_nodes.begin());
it != _nodes.end();
++it);
delete *it;
}; // eo dtor
Node* Add(const std::string& name)
{
Node* newNode = new Node(name);
_nodes.Add(newNode);
return newNode;
}; // eo Add
}; // eo class Node
| |
doc_3272
|
function gi(id){return document.getElementById(id)}
a= [1,5,1,2,3,5,3,4,3,4,3,1,3,6,7,752,23]
for(i=0; i < a.length; i++){
/*
if (WHAT AND WHAT){ What do I add here to know that the last value in the array was used? (For this example, it's the number: 23. Without doing IF==23.
}
*/
gi('test').innerHTML+=''+a[i]+' <br>';
}
(the code is also available at https://jsfiddle.net/qffpcxze/1/)
So, the last value in that array is 23, but how can I know that the last value was looped in, inside the loop itself? (Without checking for a simple IF X == 23, but dynamically), if that makes sense.
A: if (i == a.length - 1) {
// your code here
A: You can make the condition in if like this:
function gi(id){return document.getElementById(id)}
a= [1,5,1,2,3,5,3,4,3,4,3,1,3,6,7,752,23];
for(i=0; i < a.length; i++){
if (i==(a.length-1)){ //give your condition here
//your stuff
}
gi('test').innerHTML+=''+a[i]+' <br>';
}
A: You can try this:
if(i === a.length - 1) {
//some code
}
A: Write an if statement which compares the arrays length with i
if(a.length - 1 === i) {
console.log('loop ends');
}
Or you can use a ternary
(a.length - 1 === i) ? console.log('Loop ends') : '';
Demo
Also note that am using - 1 because array index starts from 0 and the length is returned counting from 1 so to compare the array with length we negate -1 .
| |
doc_3273
|
A: By definition, windowless ActiveX control doesn't have a window, and rendered as part of its parent. If you want to work with Windows messages in the control, you can create worker thread with a message loop, and handle any messages there. To have message loop, you don't need a window, just thread. This solution can be implemented in windowless control or in any COM component.
Alternatively, you can use windowed ActiveX control by changing its properties.
| |
doc_3274
|
I want get to user input multiple times without having to run the program more than once.
I would like to enter a hero and get an answer back and then be able to enter another one without hitting run over and over.
If anyone has any suggestions please let me know.
Thank you!
"""
This program is intended to compare heroes from Marvel and DC. Enter
your
hero choice and see what hero from #Marvel or DC is most like them.
I know there are simpler ways to write this code so if anyone has any
suggestions please leave them for me
Thanks for viewing!
Only the heroes below can be entered
marvel = ['Moon Knight', 'Hyperion', 'Thor', 'Punisher', 'Jean Grey',
'Iron Man', 'Quicksilver']
DC = ['Batman', 'Superman', 'Shazam', 'Red Hood', 'Wonder Woman',
'Batwing', 'Flash']
"""
choice = str(input('Choose a hero\n'))
def hero_choose():
if choice.lower() == 'batman':
return('Moon Knight')
if choice.lower() == 'moon knight':
return('Batman')
if choice.lower() == 'superman':
return('Hyperion')
if choice.lower() =='hyperion':
return('Superman')
if choice.lower() == 'thor':
return('Shazam')
if choice.lower() == 'shazam':
return('Thor')
if choice.lower() == 'red hood':
return('punisher')
if choice.lower() == 'punisher':
return('Red Hood')
if choice.lower() == 'wonder woman':
return('Jean Grey')
if choice.lower() == 'jean grey':
return('Wonder Woman')
if choice.lower() == 'iron man':
return('Batwing')
if choice.lower() == 'batwing':
return('Iron Man')
if choice.lower() == 'flash':
return('Quicksilver')
if choice.lower() == 'quicksilver':
return('Flash')
else:
return('Your hero may not be available\nor your spelling may be
wrong.')
print(hero_choose())
A: Have you considered having your user enter a comma delimited list of values? For instance
$ python choose_hero.py
Please enter hero names seperated by a "," (e.g. batman,robin)
Names: batman,superman
Moon Night
Hyperion
implemented as follows
print("Please enter hero names seperated by a \",\" (e.g. batman,robin)")
choices = [name for name in str(input('Names: ')).split(',')]
for choice in choices:
# your implementation of hero_choose will need to be modified
# to accept a param, rather than using the global choice var
hero_choose(choice)
I know this isn't the Code Review stack, but if I could make a suggestions unrelated to your issue. Consider using a Dictionary as a switch statement instead of an endless stream of if statements
| |
doc_3275
|
In "UIViewController+Ext.m":
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class vc = [UIViewController class];
SEL originalSEL = @selector(viewDidLoad);
SEL swizzledSEL = @selector(Easy_viewDidLoad);
Method originalMethod = class_getInstanceMethod(vc, originalSEL);
Method swizzledMethod = class_getInstanceMethod(vc, swizzledSEL);
BOOL didAddMethod =
class_addMethod(vc, originalSEL, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(vc, swizzledSEL, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}
else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (void)Easy_viewDidLoad
{
UIView *view = self.view ;
UIView *tempV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth(), ScreenHeight())];
tempV.backgroundColor = [UIColor cyanColor];
self.view = tempV ;
view.frame = CGRectMake(0, NavigationHeight(), ScreenWidth(), ScreenHeight()-NavigationHeight());
[self.view addSubview:view];
[self Easy_viewDidLoad];
}
When I add a UITextField on the view controller, the textfield becomes first responder. But the app is killed and throws this error:
-[UIView leftDockItem]: unrecognized selector sent to instance 0x7f91bb742d80
*
*What is the leftDockItem
*What is the base way to add a view below viewcontroller.view?
| |
doc_3276
|
I got :
an app.cfg
a spring-context.xml
a environnement.xml file wich contains specific variables values according to the where the app is running : a folder for production, one for qa, and one for test.
What I want to achieve :
in my shell (windows), before launching the app with foo.bat, I do :
set environment="qa"
When Spring loads the context, it picks the value contained in the environment var (say qa), and loads the correct file : thus replacing : configuration/{environment}/vars.xml
by configuration/qa/vars.xml.
In my my spring-context.xml file, I got objects like this : value = ${connectionString.DB1}" where the value is defined inside each vars.xml file (remember, one for prod, one for qa...).
For now, I am not able to replace the ${environment} variable. So I did it programmatically by getting the value of ${environment} with System.Environment.GetEnvironmentVariable("environnement"); and using Path.Combine, load the two contexts myself :
reader.LoadObjectDefinitions(envPath);
reader.LoadObjectDefinitions("configuration/common/springContext.xml");
BUT :
I would like to make it by configuration.
I've been playing with (with no luck) :
<object type="Spring.Objects.Factory.Config.VariablePlaceholderConfigurer, Spring.Core">
<property name="VariableSources">
<list>
<object type="Spring.Objects.Factory.Config.EnvironmentVariableSource, Spring.Core"/>
</list>
</property>
</object>
<object name="appConfigPropertyHolder"
type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core">
<property name="EnvironmentVariableMode" value="Override"/>
</object>
Any ideas ?
A: Ok, after much research, it works!
<object type="Spring.Objects.Factory.Config.VariablePlaceholderConfigurer, Spring.Core">
<property name="VariableSources">
<list>
<object type="Spring.Objects.Factory.Config.EnvironmentVariableSource, Spring.Core"/>
<object type="Spring.Objects.Factory.Config.PropertyFileVariableSource, Spring.Core">
<property name="Location" value="${root.config}/envars.properties" />
<property name="IgnoreMissingResources" value="false"/>
</object>
</list>
</property>
</object>
path to property file depends upon the environment variable.
Variables are replaced by the values obtained from the properties file.
I deploy one package + folder with 4 environment properties files
And I set my env var accordingly.
No need to mess with app.config or multiple Spring configuration files.
| |
doc_3277
|
client.on('presenceUpdate', (oldStatus, newStatus) => {
if (newStatus.length !== 0) {
newStatus.activities.forEach(element => {
if (element.name === 'Spotify') {
const obj = {
name: element.name,
spotify: element.syncId,
top: element.assets.largeText,
artist: element.details,
album: element.state,
url: element.assets?.largeImageURL(),
}
socket.emit('activity', obj);
} else if (element.name === 'Visual Studio Code') {
const obj = {
name: element?.name,
top: element.assets?.largeText,
artist: element?.details,
album: element?.state,
url: element?.assets?.largeImageURL(),
}
socket.emit('activitycode', obj);
}
oldStatus.activities.forEach(ele => {
if (ele?.nalement.name !== 'Spotify') {
socket.emit('stop')
} else if (element.name !== 'Visual Studio Code') {
socket.emit('stopcode')
}
})
})
}
This is my react part which handles it all
function About() {
const [spotify, setspotify] = React.useState();
const [code, setcode] = React.useState();
useEffect(() => {
const socket = io();
socket.on("activity", (activity) => {
setspotify(activity);
});
socket.on("stop", (activity) => {
setspotify();
});
socket.on("stopcode", (activity) => {
setcode();
});
socket.on("activitycode", (activity) => {
setcode(activity);
});
axios.get('/code').then(res => {
setcode(res.data);
});
axios.get("/activity").then((res) => {
setspotify(res.data);
});
}, []);
return (
<section className="info flex" >
<LazyLoad>
<img src='./asset/avatar.jpg' alt='avatar' width="280" height="280" sizes="280px" decoding="async" className='avatar' />
</LazyLoad>
<h1 className='title'>Instict</h1>
<p className='description'>
Developing since 2018, i have created many bugs.
</p>
<div>
{(spotify || code) && <h2 className='subtitle blogheading'>Activity</h2>}
{spotify && <div>
<div className='activity-item'>
<img src={spotify.url} alt='activity' className="activity-item-image"/>
<div className='activity-item-info'>
<h3 className='activity-item-title'>{spotify.name}</h3>
<a href={`https://open.spotify.com/track/${spotify.spotify}`}>
<p className='activity-item-description'>{spotify.artist} - {spotify.album}</p>
</a>
</div>
</div>
</div>}
{code && <div>
<div className='activity-item'>
<img src={code.url} alt='activity' className="activity-item-image"/>
<div className='activity-item-info'>
<h3 className='activity-item-title'>{code.name}</h3>
<p>{code.top}</p>
<p>{code.album}</p>
<p>{code.artist}</p>
</div>
</div>
</div>}
</div>
</section>
);
}
but if I change the say the song or the file I'm working on it stops the other one say if I change my song the socket.emit('stopcode') gets run
Fairly I have no idea how to deal with this but I am getting it's the presence update part which I have to deal with, for those wondering I use discord.js, socket.io.
example: https://gyazo.com/a60c2b51d264707ea5aaadfb9c62e096
| |
doc_3278
| ||
doc_3279
|
<script>$( "tr:contains('Novel')" ).addClass('row-highlight-novel');</script>
But what I'd like to do is the same thing, but with a link, where I could add a class to the tr based on whether it has a specific url or not.
I've tried $("a[href='http://www.link-here.org/']"), but that only selects the link, not the table row it's in. I can't seem to find the right selector that will do this for the whole table row. Your help would be much appreciated!
A: Without further context I would think using .closest() would work:
$("a[href='http://www.link-here.org/']").closest('tr')
Ref: https://api.jquery.com/closest/
A: This is how i would do it
html
<a href="http://test.com/?foo=bar&baz=quux"><tr>hello</tr></a>
<a href="http://example.ca/?foo=bar&baz=quux"><tr>hello</tr></a>
Jquery selector
$('a[href*="test"]').each(function() {
$(this).addClass('test');
});
here is complete fiddle
http://jsfiddle.net/q0nc3dzq/3/
| |
doc_3280
|
cmd.run "apt update && apt upgrade -y"
sometimes asks confirmation to overwrite config files with new version, how automatically preserve the current config file? "Y/N"
or
there are better way to update entire system via salt-stack?
A: There is the pkg module. Use it like that:
salt '*' pkg.upgrade --refresh=True
A: You can use the pkg.upgrade module, or you could schedule a pkg.uptodate state.
https://docs.saltstack.com/en/latest/ref/states/all/salt.states.pkg.html#salt.states.pkg.uptodate
And use the salt scheduler to run it periodically.
https://docs.saltstack.com/en/latest/topics/jobs/#scheduling-jobs
| |
doc_3281
|
Code:
//Get coordinates
for (int count = 1; count < ((noOfCaves*2)+1); count=count+2){
System.out.println("Cave at " + data[count] +"," +data[count+1]);
}
Output:
Cave at 2,8
Cave at 3,2
Cave at 14,5
Cave at 7,6
Cave at 11,2
Cave at 11,6
Cave at 14,1
How do I now store these locations as x,y into a list?
Thanks :)
A: Create a list of your objects
public class Cave{
private int x;
private int y
Cave(int x, int y){
this.x = x;
this.y = y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
then in your main create a list of elements:
List<Cave> caves = new ArrayList<>();
Cave c1 = new Cave(2,8);
caves.add(c1);
after populating a list, simply use for each
caves.forEach(cave -> {
System.out.println("this cave is in x:" + cave.getX()
+ " and y:" + cave.getY());
}
A: It's simple. You create a list and add the coordinates! In this case, I would a string list:
List<String> coords = new ArrayList<String>();
for (int count = 1; count < ((noOfCaves * 2) + 1); count = count + 2){
System.out.println("Cave at " + data[count] +"," + data[count + 1]);
coords.add(String.valueOf(data[count]) + "," + String.valueOf(data[count + 1]));
}
You can use String.split(",") and Integer#parseInt(String) to get the X and Y separately.
| |
doc_3282
|
which is: I want to know if there's a method or a way to get the database's value and then compare it...I'm not really sure how to explain it..so I guess I'll show you what I got so far for my code. BTW Im using netbean to make this program and im using odbc database (mircosoft access). Im also using try catch in the code but idk how to make it show..
The program below doesn't really work the way I want it too..since I'm having problems comparing.
Thanks in advance.
if(request.getParameter("username")!=null && request.getParameter("username") !=""
&& request.getParameter("password")!=null && request.getParameter("password")!=""){
String user = request.getParameter("username").toString();
String pass = request.getParameter("password").toString();
String check = "SELECT AccountType FROM Testing WHERE Username='"+user+"' AND Password ='"+pass+"'";
rs = stmt.executeQuery(check);
String info = rs.getString(check); // trying to get the AccountType and store it into a string
while(rs.next()){
if(info != null && info !=""){ //checks to see if the account exist in the database
if(info.equals("Admin")){ //checks to see if AccountType is "Admin"
response.sendRedirect("AdminConsole.jsp");
}else
response.sendRedirect("UserConsole.jsp");
}else
response.sendRedirect("ErrorPage2.jsp");
}
}else
response.sendRedirect("ErrorPage.jsp");
connection.close();
}
A: Please, please don't do this. You should not execute the SQL from within code, nor should you store passwords in plain text. What you should do is invoke a parameterized procedure that takes username/password as arguments and then returns roles (or whatever else you want). Password should still be hashed at a minimum.
Something like this: http://www.daniweb.com/software-development/csharp/threads/87556
In MS Access the Stored Procedure is referred to as a stored query:
http://msdn.microsoft.com/en-us/library/aa140021(v=office.10).aspx
Relevant parts:
Proc:
create procedure ValidateUserLogin
@UserName varchar(30)
, @Password varchar(30)
as
begin
if exists (select * from UsersTable as ut
where ut.UserName = @UserName AND ut.Password = @Password)
select 1;
else
select 0;
end
Class
private bool IsValidatedUser( string username, string password ) {
try {
bool rv = false;
using ( SqlConnection con = new SqlConnection( connectionString ) ) {
using ( SqlCommand cmd = new SqlCommand() ) {
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "ValidateUserLogin";
cmd.Parameters.Add( "@UserName", SqlDbType.VarChar, 30 ).Value = username;
cmd.Parameters.Add( "@Password", SqlDbType.VarChar, 30 ).Value = password;
rv = Convert.ToBoolean( cmd.ExecuteScalar() );
con.Close();
}
}
return rv;
}
catch ( Exception ex ) {
// Log errors
throw;
}
}
| |
doc_3283
|
http://www.borngroup.com/work/dkny/
It looks like the change is made via javascript to each element's background color but I cant figure out how this is achieved.
Any help would be much appreciated!
A: I don't know if this is what borngroup is doing, but you can accomplish this sort of effect using just css with background images and background-attachment: fixed.
Here's a quick demonstration.
body {
height: 1000px;
}
#one {
background-color:black;
background-image: url('http://d.pr/i/18pT3+');
background-attachment: fixed;
background-repeat: no-repeat;
height:100px;
}
#two {
background-color:yellow;
background-image: url('http://d.pr/i/1capU+');
background-attachment: fixed;
background-repeat: no-repeat;
height:100px;
}
| |
doc_3284
|
<div id='container' width='300'>
<div id='left' width='150'></div>
<div id='right' width='150'></div>
</div>
I know you can use float to achieve the goal but I want to know the cause.
JSFiddle here.
Also I have noticed when I get the width() of an element I didn't get the same number what's in the debug window. Any clue?
Thanks!
Edit: OK, I see know it's a ' ' between them because of the new line character. It doesn't seems to matter if it's 'inline-block' or 'block' though. However setting the container to display as 'flex' appears to be a solution.
(Also thank you for the suggestions on how to remove the space even if there are white space characters between the divs! I still can't upvote sadly because of low reputation...)
A: Compare:
<div>
a
b
</div>
with:
<div>
ab
</div>
Elements that are display: inline-block are treated like text.
There is space between them because they are inline elements with white space characters between them in the markup.
Put the start tag for the second div immediately after the end tag for the first one, without any spaces, tabs or new lines between them.
A: The problem is that inline/inline-block elements respect white spaces, including new line characters, they also take space. Hence, if you remove all white spaces between elements it will fix the issue:
<div id='container'>
<div id='left'> </div><div id='right'> </div>
</div>
Demo: http://jsfiddle.net/za2uu8ze/2/
Of course manually (or programmatically) remove all spaces between tags is not very elegant solution. Unfortunately there is no clean CSS property to ignore them. However you can set font-size: 0 on wrapping container level and reset it back to necessary font value on elements level. This will effectively make white spaces 0-size:
#container {
/* ... */
font-size: 0;
}
#container > * {
font-size: 16px;
}
Demo: http://jsfiddle.net/za2uu8ze/3/
A: Its because of inline-block element:-
You can try like this:-
<div id='container'>
<div id='left'> </div><div id='right'> </div>
</div>
OR
<div id='container'>
<div id='left'> </div><!--
--><div id='right'> </div>
</div>
| |
doc_3285
|
Please explain,
Here is my code
server.c
#include "head.h"
void readstr(int connfd ,char [][20]);
//void writestr(char * ,int);
int main(int c ,char *v[])
{
int sd,connfd,retbind;
struct sockaddr_in serveraddress ,cliaddr;
socklen_t len;
char buf[100] ,databuf[1024][4];
sd =socket( AF_INET ,SOCK_STREAM ,0);
if (sd<0)
{
exit(1);
}
memset(&serveraddress ,0 ,sizeof(serveraddress));
serveraddress.sin_family =AF_INET;
serveraddress.sin_port =htons(MYPORT);
serveraddress.sin_addr.s_addr =htonl(INADDR_ANY);
retbind =bind(sd ,(struct sockaddr*)&serveraddress ,sizeof(serveraddress
));
if(-1 ==retbind)
{
perror("bind fails ");
exit(0);
}
listen(sd ,4);
for(;;)
{
printf("i am waiting for client\n");
len =sizeof(cliaddr);
connfd = accept(sd ,(struct sockaddr*)&cliaddr ,&len);
if(connfd <0)
{
if(errno ==EINTR)
printf("interrupt");
continue;
}
printf("connection from %s\n",inet_ntop(AF_INET ,&cliaddr.sin_addr,buf ,
sizeof(buf)));
readstr(connfd ,databuf);
close(connfd);
printf("\n fini one clieni");
}
return 0;
}
void readstr(int connfd ,char str[3] [20])
{
int pointer=0 ,i=0, n,pos=0;
memset(str ,'\0',sizeof(str));
printf("\n->Connfd : %d\n",connfd);
printf("\n----->String recieved : %s\n",str);
for(i=0;i<3;i++)
{
while((n=read(connfd ,str[i] ,20)) >>0)
{
printf("Looping while\n");
pos =pos +n;
}
str[i][pos] ='\0';
}
for(i=0;i<3;i++)
{
printf("\n%s",str[i]);
}
}
client.c
#include "head.h"
void send1(int ,char*);
int main(int c,char*v[])
{
int sd,i;
int len;
char buf[20][4];
struct sockaddr_in serveraddress;
sd = socket(AF_INET ,SOCK_STREAM ,0);
if (sd<0)
perror("socket");
memset(&serveraddress ,0 ,sizeof(serveraddress));
serveraddress.sin_family =AF_INET;
serveraddress.sin_port =htons(atoi(v[1]));
serveraddress.sin_addr.s_addr =inet_addr(v[2]);
if(connect(sd,(struct sockaddr*)&serveraddress ,sizeof(serveraddress)) <
0)
{
printf("cannot connect to server");
exit(1);
}
for(i=0;i<3;i++)
{
memset(buf ,'\0',sizeof(buf));
printf("\n string");
fgets(buf[i],20,stdin);
len =strlen(buf[i]);
if(buf[i][len] =='\n')
buf[i][len]='\0';
// scanf("%s",buf[i]);
send1(sd ,(char *)buf);
}
shutdown(sd ,SHUT_WR);
}
void send1(int sd ,char *str)
{
int n ,byteswritten =0, wr;
char buf[1024];
strcpy(buf ,str);
n =strlen(buf);
while(byteswritten < n)
{
printf("\nStart writing in client side\n");
wr = write(sd , buf+byteswritten ,(n-byteswritten));
byteswritten+=wr;
}
printf("\n string sent %s" ,buf);
}
A: In client.c main:
char buf[20][4];
change to:
char buf[4][20];
In server.c readstr:
while((n=read(connfd ,str[i] ,20)) >>0)
change to:
while((n = read(connfd, &str[i][pos], 20)) > 0)
pos needs to be reset to 0 inside the for loop.
Also, the client reads 3 strings of up to 20 chars each from stdin and writes them to the socket.
The server expects 3 strings of exactly 20 chars each.
You should either use some kind of record separator, like \n, in your network protocol, or use fixed length, i.e. pad the input strings to 20 characters.
There may be more errors in your code, I stopped looking after finding these.
A: It has been over 1 hour on SO and you haven't got an answer.. to what seems like a very simple problem(odd feat). you know why?
*
*because its very painful to go through your code.
*
*document it!
*divide it into modules - init_net(), form_pkt(),
send_pkt(), exit(),.. etc
*describe your problem properly.
*
*how many client are you running?
*what happens after only first strings get printed. does you code stops, loops forever what?
*have you looked through a packet capture tool like tcpdump, wireshark, etc
*and before I get to the main problem.. I see things like "databuf[1024][4]" being passed to a function readstr() with formal arguments "char str[3] [20]".
*
*couple of advice
*
*run your code through a static tool analyzer to look for basic warnings.
*strings are not a great idea to send on network, learn how to define a packet structure with header and data part, etc
*also I believe you are looking for a Packet like communication instead of stream based. understand the difference!
I do not know the answer to that question unless you present it properly. this time and every next time.
| |
doc_3286
|
If anyone is aware of this, please share the link, it will be helpful for me.
Thanks.:)
A: Assuming you are talking about IBM MQ.
There is currently no support for an IBM MQ Windows image. The only platform that is supported as a containerized platform is Linux.
Source: No mention of any other platform than Linux on the Configuring IBM MQ in Docker Knowledge Center page
Now in theory you could create one by hand using the sample MQ Dockerfile and config files available on GitHub as a basis. However if you encounter problems with this then you won't be able to get any help from IBM.
That said. If you are talking about running the IBM MQ Docker image on a windows machine (so the host machine docker is installed on is Windows) then you can still run the Linux image inside that docker. For windows docker installs a VM where it runs the images and this VM generally is Linux meeting the requirements set out on the Docker support on Linux systems Knowledge Center page
| |
doc_3287
|
I was trying to use CoreAudio API I created ImmNotificationClient.cs interface
[Guid("7991EEC9-7E89-4D85-8390-6C703CEC60C0"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMMNotificationClient
{
/// <summary>
/// Device State Changed
/// </summary>
void OnDeviceStateChanged([MarshalAs(UnmanagedType.LPWStr)] string deviceId, [MarshalAs(UnmanagedType.I4)] EDeviceState newState);
/// <summary>
/// Device Added
/// </summary>
void OnDeviceAdded([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId);
/// <summary>
/// Device Removed
/// </summary>
void OnDeviceRemoved([MarshalAs(UnmanagedType.LPWStr)] string deviceId);
/// <summary>
/// Default Device Changed
/// </summary>
void OnDefaultDeviceChanged(EDataFlow flow, ERole role, [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId);
/// <summary>
/// Property Value Changed
/// </summary>
/// <param name="pwstrDeviceId"></param>
/// <param name="key"></param>
void OnPropertyValueChanged([MarshalAs(UnmanagedType.LPWStr)] string pwstrDeviceId, PropertyKey key);
}
I have created CMMNotificationClient.cs class which implements above methods
Now I am not sure How to register the call back to these methods and register for Plug and UnPlug Events
I tried to register it in the IMMDeviceEnumerator
[PreserveSig]
int RegisterEndpointNotificationCallback(IMMNotificationClient pClient);
[PreserveSig]
int UnregisterEndpointNotificationCallback(IMMNotificationClient pClient);
Can you please help on this or can you provide any other solution?
A: You can use RegisterDeviceNotification Windows API to get notified.
Stackoverflow example
CodeProject example
| |
doc_3288
|
But i want to creat an automate which will read those file automatically.
This is an example of my XML files :
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="../StyleSheets/VDD11.xsl" type="text/xsl"?>
<Publication xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ID="F592" type="Fiche d'information" xsi:noNamespaceSchemaLocation="../Schemas/2.3/Publication.xsd">
<dc:title>Secteur privé : activité partielle du salarié</dc:title>
<dc:creator>Direction de l'information légale et administrative</dc:creator>
<dc:subject>Formation - Travail, Ressources humaines</dc:subject>
<dc:description>Lorsqu'une entreprise est confrontée à une baisse temporaire d'activité, elle peut réduire la durée du travail des salariés concernés. Ceux-ci perçoiv</dc:description>
<dc:publisher>Direction de l'information légale et administrative</dc:publisher>
<dc:contributor>Direction de l'information légale et administrative (Premier ministre)</dc:contributor>
<dc:date>modified 2013-07-03</dc:date>
<dc:type>Fiche</dc:type>
<dc:format>text/xml</dc:format>
<dc:identifier>F592</dc:identifier>
<dc:source>http://www.legifrance.gouv.fr/affichCode.do?cidTexte=LEGITEXT000006072050, http://circulaires.legifrance.gouv.fr/pdf/2013/07/cir_37288.pdf</dc:source>
<dc:language>Fr</dc:language>
<dc:relation>isPartOf N31002</dc:relation>
<dc:coverage>France entière</dc:coverage>
<dc:rights>http://www.service-public.fr/apropos-du-site/001371.html</dc:rights>
<Audience top="false">Particuliers</Audience>
<Audience top="false">Professionnels</Audience>
<Canal>www.service-public.fr</Canal>
<FilDAriane>
<Niveau ID="N24267">Ressources humaines</Niveau>
<Niveau ID="N10813">Réglementation du travail</Niveau>
<Niveau ID="N31002">Chômage partiel</Niveau>
</FilDAriane>
<Theme ID="N24267">Ressources humaines</Theme>
<SousThemePere ID="N10813">Réglementation du travail</SousThemePere><DossierPere ID="N31002">
<Titre>Chômage partiel</Titre>
<Fiche ID="F592">Règles de l'activité partielle du salarié</Fiche>
<Fiche ID="F23503">Démarches de l'employeur</Fiche>
<Fiche ID="F13898">Rémunération d'un salarié placé en activité partielle</Fiche>
</DossierPere>
<Introduction>
<Texte><Paragraphe>Lorsqu'une entreprise est confrontée à une baisse temporaire d'activité, elle peut réduire la durée du travail des salariés concernés. Ceux-ci perçoivent en contrepartie une indemnité durant les périodes non travaillées.</Paragraphe>
</Texte>
</Introduction>
<Texte><Chapitre>
<Titre>
<Paragraphe>Conditions du recours à l'activité partielle</Paragraphe>
</Titre><SousChapitre>
<Titre>
<Paragraphe>Entreprises concernées</Paragraphe>
</Titre><Paragraphe>
<LienInterne LienPublication="F23503" type="Fiche d'information" audience="Professionnels">L'employeur</LienInterne> peut demander à placer tout ou partie des salariés en position d'activité partielle lorsque l'entreprise est contrainte de réduire ou de suspendre temporairement son activité pour l'un des motifs suivants :</Paragraphe><Liste type="puce">
<Item>
<Paragraphe>une conjoncture économique défavorable (baisse des commandes, par exemple),</Paragraphe>
</Item>
<Item>
<Paragraphe>des difficultés d'approvisionnement en matières premières ou en énergie,</Paragraphe>
</Item>
<Item>
<Paragraphe>un sinistre (ou des intempéries) ou toute autre circonstance de caractère exceptionnel (perte du principal client, par exemple), ayant entraîné l'interruption ou la réduction de l'activité,</Paragraphe>
</Item>
<Item>
<Paragraphe>la transformation, restructuration ou modernisation de l'entreprise.</Paragraphe>
</Item>
</Liste>
</SousChapitre>
<SousChapitre>
<Titre>
<Paragraphe>Salariés concernés</Paragraphe>
</Titre><Paragraphe>Tout salarié peut être placé en position d'activité partielle, s'il subit une perte de rémunération causée :</Paragraphe>
<Liste type="puce">
<Item>
<Paragraphe>soit par la fermeture temporaire de tout ou partie de l'établissement,</Paragraphe>
</Item>
<Item>
<Paragraphe>soit par la réduction de l'horaire de travail en deçà de la durée légale de travail.</Paragraphe>
</Item>
</Liste>
<Paragraphe>En cas de réduction collective de l'horaire de travail, le placement en activité partielle peut être individuel ou concerner les salariés alternativement.</Paragraphe>
</SousChapitre>
</Chapitre>
<Chapitre>
<Titre>
<Paragraphe>Rémunération</Paragraphe>
</Titre><Paragraphe>Pendant les périodes non travaillées, le salarié perçoit une indemnité d'activité partielle, versée par l'employeur.</Paragraphe>
<Paragraphe>Le salarié dont la durée du travail est fixée par forfait en heures ou en jours sur l'année en bénéficie seulement en cas de fermeture totale de l'établissement ou d'une partie de l'établissement dont il relève.</Paragraphe>
<ANoter><Paragraphe>
<MiseEnEvidence>À noter : </MiseEnEvidence>les salariés en chômage partiel avant le 1er juillet 2013 bénéficient de <LienInterne LienPublication="F24640" type="Fiche Question-réponse" audience="Professionnels">règles d'indemnisation différentes</LienInterne>.</Paragraphe>
</ANoter>
<SousChapitre>
<Titre>
<Paragraphe>Montant</Paragraphe>
</Titre><Paragraphe>Le montant de l'indemnité d'activité partielle est fixé à <MiseEnEvidence>70 %</MiseEnEvidence> de la rémunération brute.</Paragraphe>
<Paragraphe>Lorsque le salarié suit une action de formation, le montant de l'indemnité est porté à <MiseEnEvidence>100 %</MiseEnEvidence> de la rémunération nette.</Paragraphe>
<Paragraphe>Pour les salariés en <LienInterne LienPublication="F22424" type="Fiche d'information" audience="Professionnels">contrat d'apprentissage ou de professionnalisation</LienInterne>, le montant ne peut pas être supérieur au montant de l'indemnité horaire due par l'employeur.</Paragraphe>
</SousChapitre>
A: You first have to come up with a way which can read xml files from a directory as bellow. (assuming you don't want to hard code 2000 file paths ;) )
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "file Path : .".$dir."/".$file."<br />";
}
closedir($dh);
}
}
Within while loop you can read xml file and parse it using xslt by php Dom.
Btw for 2000 xmls this will take some time to finish execute, i guess. :)
| |
doc_3289
|
<div>
<object>
<embed src="..."> <!-- no attributes except src -->
</object>
</div>
<style>
div { height: 300px; }
object, embed { height: 100%; }
</style>
Instead of expected behaviour I get the flash of absolutely other size: it is much smaller than it's parent in all dimensions. Actually, I don't understand why it takes this particular size - it looks too small (like zoomed out few times).
To make it to behave in a proper way I have to set both width and height for explicitly. It may be done both inline and in CSS.
The question is: why doesn't it calculate height (though it obviously has enough data - <img> can resize properly at the same conditions) based on parent's height and given percentage?.
(Initially I've had many other attributes (including duplicated width and height on both and tags) which all I removed to simplify the example. While doing that, I was checking whether removement changes anything and it didn't except of width and height attributes.)
| |
doc_3290
|
DOM structure description here
I tried making changes by following code
let host = document.querySelector(".fs-timescale-dd");
// host.setAttribute('style','font-style:normal');
let child= host.querySelector('.select');
child.querySelector('.ng-select').querySelector('.ng-select-container')
.querySelector('ng-value-container').querySelector('ng-placeholder')
.setAttribute('style','font-style:normal');
But I'm getting TypeError: Cannot read properties of null (reading 'querySelector')
I'm new to Angular, can someone please help.
A: You have not clearly mentioned your goal. After reading your question what I can understand is you want to change the font style of the options of the dropdown. If so you can do this from the following example. You can directly select the class on which you want to apply the style.
::ng-deep .some-class {
font-style: normal;
}
A: Solved by referencing the shadow dom element by adding a class name to it.
Something like this -
document.querySelector(".fs-timescale-dd").className('someName').shadowRoot.setAttribute("font","arial")
| |
doc_3291
|
$data = $this->request->data;
$conditions = array('authenid' => $data['id'], 'isblacklist' => $data['isblacklist']);
if( $data['key'] == "msisdn" ) {
if(isset ($data["search"])){
if( trim($data["search"]) != "" ) {
$conditions[ "CONCAT(msisdn,',',ton,',',npi) LIKE" ] = "%".trim($data["search"])."%";
}
}
$tmpData = $this->blkwhtlist_msisdn->find('all', array(
'conditions' => $conditions
));
A: I guess you are trying querys in mysql db:
CONCAT is a string function to concatenate in mysql:
CONCAT('abc', '.de') that return a string 'abc.de'
And the LIKE is a mysql operator used to select data based on patterns. Therefore the LIKE operator is often used in the WHERE clause of the SELECT statement. mysql provides two wildcard characters for using with the LIKE operator, the percentage % and underscore _.
*
*The percentage ( %) wildcard allows you to match any string of zero
or more characters.
*The underscore ( _) wildcard allows you to match
any single character.
| |
doc_3292
|
For clarity I mean they may have
functionName() {
return this.http.get(this.url).
pipe(
timeout(5000)
)
}
As you can see in my code below, my observable is setup upon creation right away. I've tried using timeout as directed in documentation, but that appears be using that function approach.
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private http: HttpClient) { }
private baseAPIURL: string = environment.baseAPIUrl;
private apiUrl = `${this.baseAPIURL}/Product/GetProduct`;
private searchSubject = new BehaviorSubject<ProductSearch>(null);
searchSelectedAction$ = this.searchSubject.asObservable();
productOutput$ = this.searchSelectedAction$
.pipe(
skip(1),
switchMap(searchCriteria =>
this.http.get<ProductResults>(`${this.apiUrl}/${searchCriteria.key1}/${searchCriteria.key2}`, { observe: 'response' })),
timeout(5000),
map(response => [response.body]),
tap(data => console.log(data))
);
getProductResults(searchCriteria: ProductSearch): void {
this.searchSubject.next(searchCriteria);
}
}
Expected result is to have the http request cancelled after 5 seconds and an error displayed that the request has been cancelled.
Actual result right now is that once the page loads the timeout starts right away without even having done a search.
I am using RxJS 6. My html is just setup to subscribe to productOutput$ using an async pipe.
A: If I don't misunderstand your question, this can be solved with either:
*
*Use Subject and not BehaviourSubject, or..
*Use filter(x=> x !== null) prior to the HTTP call. This will ensure that none of the operators after the filter will get called. Feel free to update the filter operator according to your need
| |
doc_3293
|
DownloadTaskProcessor
public class DownloadTaskEnqueuer {
private static final BlockingQueue<Task> downloadQueue = new LinkedBlockingQueue<>();
private static final BlockingQueue<Task> processQueue = new LinkedBlockingQueue<>();
private static final ExecutorService executor = Executors.newCachedThreadPool();
public void offer(Task task) {
return downloadQueue.offer(task);
}
public void createPool(int size) {
for (int i = 0; i < size; i++) {
executor.execute(new DownloadTask(downloadQueue, processQueue);
executor.execute(new ProcessTask(processQueue));
}
}
}
Download task
public class DownloadTask implements Runnable {
private BlockingQueue<Task> downloadQueue;
private BlockingQueue<Task> processQueue;
// constructor for initing two queue
public void offer(Task task) {
return processQueue.offer(task);
}
@Override
public void run() {
while (true) {
Task task = downloadQueue.poll();
if (task != null) {
task.getDownloadTask().download();
offer(task);
} else {
// sleep 250 ms
}
}
}
}
Process task
public class ProcessTask implements Runnable {
private BlockingQueue<Task> processQueue;
// constructor for initing queue
@Override
public void run() {
while (true) {
Task task = processQueue.poll();
if (task != null) {
task.getProcessTask().process();
} else {
// sleep 250 ms
}
}
}
}
Use case (pseudo)
createPool(10);
listener.listen((task) -> {
downloadTaskEnqueuer.offer(task);
}
A: There are some design mistakes. Everyyime you write Thread.sleep() than you implementing the busy waiting pattern. This is not recommended.
Just try this:
public class DownloadTaskEnqueuer implements Runnable {
private final BlockingQueue<Task> queue = new LinkedBlockingQueue<>();
private final LinkedList<Future<Object>> results = new LinkedList<>();
private final Semaphore lock = new Semaphore(0);
boolean isRunning = true;
private final ExecutorService executor;
public DownloadTaskEnqueuer(int parallismCount) {
executor = Executors.newFixedThreadPool(parallismCount);
}
public void offer(Task task) {
queue.offer(task);
lock.release();
}
@Override
public void run() {
while (isRunning) {
lock.acquireUninterruptibly();
Task task = queue.poll();
Future<Object> futureResult = executor.submit(task);
results.add(futureResult);
}
}
public static void main(String[] args) {
DownloadTaskEnqueuer dte = new DownloadTaskEnqueuer(10);
Thread t = new Thread(dte);
t.start();
}
public abstract class Task implements Callable<Object> {
abstract Object download();
abstract Object doProcess(Object downloadedObject);
@Override
public Object call() throws Exception {
Object downloadedObject = download();
Object processingResult = doProcess(downloadedObject);
return processingResult;
}
}
| |
doc_3294
|
file application.ts
class
APPLICATION{
constructor(){
console.log("constructor APPLICATION")
this.database = new REPOSITORY
}
database: REPOSITORY
}
new APPLICATION
import { REPOSITORY } from "./repository"
file repository.ts
export
class
REPOSITORY {
constructor() {
console.log("constructor de REPOSITORY")
}
}
ANd I get the error
this.database = new repository_1.REPOSITORY;
^
TypeError: Cannot read property 'REPOSITORY' of undefined
at new APPLICATION (Z:\Documents\Phi\Developpement\TypeScript\test\application.js:6:41)
Any Idea ?
A: You are perfectly right !
I thought that the compiler was in two-passes and that the order of these statements were not imposed.
As I think that this import/export mecanism should be automatic, I would prefer to hide it at the end of the code ! Too bad !
Thank you
A: Your import statement for REPOSITORY occurs after REPOSITORY is used in the constructor for APPLICATION, which means that it is not yet defined in the constructor (the variable assignment resulting from the import statement is not hoisted). You will need to import prior to use:
import { REPOSITORY } from "./repository"
class APPLICATION {
constructor(){
console.log("constructor APPLICATION")
this.database = new REPOSITORY();
}
database: REPOSITORY
}
A: I don't believe imports are hoisted. Try moving import { REPOSITORY } from "./repository" up in your code.
| |
doc_3295
|
I have a function called execute in tab1, which I would like to call from the page in tab2.
Is that possible and if so how?
A: JavaScript can not do cross-tab scripting in the browser (it is a security risk).
If however the second tab was opened from a window.open() call, and the browsers settings were set up such that new popup windows open in a new tab instead -- then yes, "tab1" can talk to "tab2".
The first tab/window is called the opener and thus the new tab can call functions on the opener using this format:
opener.doSomething();
Likewise, the opener can call functions on the new tab/popup, by using the variable it created when creating the popup window.
var myPopup = window.open(url, name, features);
myPopup.doStuffOnPopup();
A: There's a tiny open-source component to sync/lock/call code in multiple tabs that allows you send messages between tabs (DISCLAIMER: I'm one of the contributors!)
https://github.com/jitbit/TabUtils
That can be called like this:
TabUtils.BroadcastMessageToAllTabs("messageName", data);
And then in another tab:
TabUtils.OnBroadcastMessage("messageName", function (data) {
//do something
});
It is based on the onstorage event, you can simply modify the code for you need, it's very simple.
A: You should show your HTML in the first place, but I assume your tab has a link, and you could it do like this:
<a href="some-path" id="tab2">Tab 2</a>
jQuery:
$('#tab2').click(function(){
// Your function code here
// Prevent the default action
return false;
})
A: You can pass JavaScript function references as arguments to other functions (be wary of object execution contexts).
So while initializing "tab2", you could send in the function reference of execute of "tab1", to "tab2".
| |
doc_3296
|
This is the simple code I've been trying to run without the console showing up.
#include <iostream>
#include "SDL.h"
int main(int argc, char* argv[])
{
if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
std::cout << "I";
return 0;
}
And these are the errors I keep getting:
'finstream.exe' (Win32): Loaded 'C:\Users\Sorin\Desktop\finstream\x64\Debug\finstream.exe'. Symbols loaded.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\ntdll.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\kernel32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\KernelBase.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\vcruntime140d.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Users\Sorin\Desktop\finstream\finstream\SDL2.dll'. Module was built without symbols.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\msvcp140d.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\vcruntime140_1d.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\advapi32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\ucrtbased.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\msvcrt.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\sechost.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\ucrtbased.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Unloaded 'C:\Windows\System32\ucrtbased.dll'
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\rpcrt4.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\gdi32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\win32u.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\ole32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\gdi32full.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\msvcp_win.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\ucrtbase.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\ucrtbase.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Unloaded 'C:\Windows\System32\ucrtbase.dll'
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\user32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\user32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Unloaded 'C:\Windows\System32\user32.dll'
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\combase.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\imm32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\oleaut32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\setupapi.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\shell32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\version.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\winmm.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\uxtheme.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\SHCore.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\kernel.appcore.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\bcryptprimitives.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\clbcatq.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\MMDevAPI.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\devobj.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\cfgmgr32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\cfgmgr32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Unloaded 'C:\Windows\System32\cfgmgr32.dll'
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\cfgmgr32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Unloaded 'C:\Windows\System32\cfgmgr32.dll'
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\avrt.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\dinput8.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\InputHost.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\CoreMessaging.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\hid.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\cryptbase.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\wintrust.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\crypt32.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\msasn1.dll'. Symbol loading disabled by Include/Exclude setting.
'finstream.exe' (Win32): Loaded 'C:\Windows\System32\XInput1_4.dll'. Symbol loading disabled by Include/Exclude setting.
The thread 0x2ae0 has exited with code 0 (0x0).
The thread 0x60ac has exited with code 0 (0x0).
The thread 0x6b6c has exited with code 0 (0x0).
The thread 0x4dbc has exited with code 0 (0x0).
The thread 0x4668 has exited with code 0 (0x0).
The thread 0xaa4 has exited with code 0 (0x0).
The thread 0x5ddc has exited with code 0 (0x0).
The program '[32192] finstream.exe' has exited with code 0 (0x0).
Keep in mind that this works just fine when the SubSystem is set to console.
EDIT: I'm using visual studio.
| |
doc_3297
|
js:
var get_url = '/tracks';
var get_options = {
q:'x',
limit:6,
linked_partitioning: 1
}
SC.get(get_url,get_options)
.then(function(data){
console.log(data);
});
url for result:
https://api.soundcloud.com/tracks?q=x&limit=6&linked_partitioning=1&format=json&client_id=d652006c469530a4a7d6184b18e16c81.
limit is set to 6 and only 4 items return.
why?
| |
doc_3298
|
*
*3D Math
*Game Design
*Physics for Game programmer
*AI for for Game programmer
*DirectX, OpenGL
Regards,
picarodevosio
A: There's a series of lectures on computer graphics from Utrecht University.
A: Microsoft has a toolkit called XNA that covers a lot of material, but it is all proprietary to their platform (XBox, Zune, PC). You can read up on it by going to MSDN and search for XNA. Their dev community is pretty active.
A: Why do you need video lectures rather than books? There are many useful books on the subject, more than there are useful lectures.
| |
doc_3299
|
[
{
"classes": [
{
"class_name": "fist class",
"sections": [
{
"section_name": "section a"
},{
"section_name": "section b"
}
]
},
{
"class_name": "second class",
"sections": [
{
"section_name": "sect a"
},
{
"section_name": "sec b"
},
{
"section_name": "sec c"
}
]
}
],
"name": "testing",
}
]
I want to update section name for particular class name,
I tried in many ways using filters also can anyone help me out
A: You want to use arrayFilters with $s[] the positional operator
db.collection.updateMany(
{},
{
$set: {
'classes.$[elem1].sections.$[elem2].section_name': 'section b'
}
},
{
arrayFilters: [
{'elem1.class_name': 'second class'},
{"elem2.section_name": "sec b"},
]
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.